简体   繁体   English

列表理解而不保存它与单行循环

[英]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. 在以下三种情况下,这是符合pythonic和样式指南的操作方式。

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. 或任何更好的方法,即一个for循环生成多个列表并分配var。

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. 除非您确实想要列表生成,否则不要使用列表推导,也不要将for循环塞入一行以使它成为单线。 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. 更加清晰,不需要读者识别解压缩的习惯用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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