简体   繁体   English

为什么使用zip对象的列表理解导致空列表?

[英]Why does list comprehension using a zip object results in an empty list?

f = lambda x : 2*x
g = lambda x : x ** 2
h = lambda x : x ** x
funcTriple = ( f, g, h )
myZip = ( zip ( funcTriple, (1, 3, 5) ) )
k = lambda pair : pair[0](pair[1])

# Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ?

print ("\n\nOutput # 1:  for pair in myZip: k(pair) ...")
for pair in myZip :
    print ( k(pair) )

print ("\n\nOutput # 2:  [ k(pair) for pair in myZip ] ...")
print ( [ k(pair) for pair in myZip ] )

# script output is ...
# Output # 1:  for pair in myZip: k(pair) ...
# 2
# 9
# 3125
# 
# Output # 2:  [ k(pair) for pair in myZip ] ...
# []

Works perfectly in Python 2.6 but fails in Python 3.0 because zip returns a generator-style object and the first loop exhausts it. 在Python 2.6中完美运行但在Python 3.0中失败,因为zip返回一个生成器样式的对象,第一个循环耗尽它。 Make a list instead: 改为列出一个清单:

myZip = list( zip ( funcTriple, (1, 3, 5) ) )

and it works in Python 3.0 它适用于Python 3.0

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

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