Python for loop completion

I am a bit confused about how to put a for loop at the end of a line in python, for example

for i in x:
    print i

produces the expected result, but if I run

print i for i in x

I get a syntax error. Can someone explain a little more about how one goes about putting your loops at the end of a line like this.

+4
source share
5 answers

In earlier versions of Python, the idea of ​​understanding lists was implemented to put together these two code templates:

# Go through each item in a list and run a test on them
# build a new list containing only items that pass the test

results = []
for item in somelist:
    if sometest(item):
        results.add(item)

and

# build a new list by changing every item in a list in the
# same way

results = []
for item in somelist:
    results.add(2 * item)

adding a new syntax that includes doing all three things in one - changing elements and / or testing them to include only some of the results and create a list of results:

results = [2 * item for item in somelist if sometest(item)]
# results is a list

[], "" Python, .

, , Python - , , , , , .

, -, () [], :

somelist = [1,2,3,4,5]
results = (2 * item for item in somelist if sometest(item))
# results is a generator

, :

function((2 * item for item in somelist)) 

, :

function(2 * item for item in somelist)

, for , .

, :

>>> print (item for item in [1,2,3])
<generator object <genexpr> at 0x7fe31b8663c0>

, , Python 2.x, , , ^^ - , .

:

>>> print [item for item in [1,2,3]]
[1,2,3]

, - , , , .

- ( , , , , -).

+4

. , , x for x in iter. a for , for x in iter genexp.

Python3 :

print(*(i for i in x))

@wim , "for loopy",

print(*(i for i in x), sep='\n')

, , xp, , , i**2 for i in x x, i for i in x if i%2 x ..

x, ( * *args ..) print

+1

:

  • - , , , , .
  • Python 3, print from __future__ import print_function Python 2.x

, , for ... print i, :

[print(i) for i in x]

( "" )

PS, , , , , .

+1

x

Python.

( x)

[ x]

[print i for i in x]

print , .

+1

, , python 2.x:

print '\n'.join(str(i) for i in x)

. for, , .

- , :

for i in x: print i

But it violates pep8, so I will not write such a line in a script.

+1
source

Source: https://habr.com/ru/post/1531448/


All Articles