简体   繁体   中英

List comprehension without saving it vs single line for loop

which is a pythonic and style guide compliant way of operation in case of the following three scenarios.

sq, div2 = [], []

# 1 Classic for loop
for i in range(10):
    sq.append(i**2)
    div2.append(i/2)

# 2 ListComp
[(sq.append(i**2), div2.append(i/2)) for i in range(10)]

# 3 single line for loop
for i in range(10):(sq.append(i**2), div2.append(i/2))

# this is also there but will have multiple loops
sq, div2 = [[i**2 for i in range(10)], [i/2 for i in range(10)]]

or any better way whereby a single for loop generates multiple lists and assign vars.

The first is absolutely the best choice of the four you list.

Don't use a list comprehension unless you actually want the list it produces, and don't cram a for loop on to one line just to make it a one-liner. Having two loops seems a definite drawback to the fourth; you are repeating yourself a bit more than necessary, although you should profile to see if the double iteration makes a significant difference in the runtime. I suspect you would need to be generating very long lists before the difference between one loop and two really matters, though.


However, there is one option you have overlooked: producing a sequence of tuples, then "unzipping" it into a tuple of tuples .

sq, div2 = zip(*((i**2, i/2) for i in range(10)))

I think I would still prefer to see the first one, though. It's clearer, without requiring the reader to recognize the unzip idiom.

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