简体   繁体   中英

How to put statement before for-loop in python

How can one put statement before for-loop in python? Such as:

print i for i in range(10)

The above example may seems unnecessary. But when it comes to a more complicated generator, it might be handy and pythonic:

print i for i in takewhile(lambda x: x < 100000, fibonacci()) if i % 2 == 0

Of course the above statements would be complained by the interpreter. There should be some standard and simple way to do it, but I just can't find it. I know I can do something similar with list comprehension:

print [i for i in range(10)]

But it prints a list rather than every i in the list. Not exactly what I want.

You can't do this in Python.

You can put it after instead:

for i in range(10): print i 

But usually you would write this on two lines.

for i in range(10):
    print i 

I guess you don't like the easy way?

for i in range(10):
    print i

If you really want the syntax you're talking about, you could try this:

from __future__ import print_function # Added in 2.6

map(print, range(10))

Here is an alternative:

print '\n'.join(map(str, range(10)))

Or a generator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM