简体   繁体   English

Python:为什么列表理解会产生一个生成器?

[英]Python: why does list comprehension produce a generator?

a=[['1','3','2'],['11','22','33']]
k = [(float(a[i][j]) for j in range(0,3)) for i in range(0,2)]
>>> print k
[<generator object <genexpr> at 0x7f1a9d568f50>, <generator object <genexpr> at 0x7f1a9d568fa0>]

but I want to get [(1,3,2),(11,22,33)] why does list comprehension produce a generator? 但是我想得到[(1,3,2),(11,22,33)]为什么列表理解会产生一个生成器?

You have a generator expression ( (x for x in ...) ) inside a list comprehension ( [x for x in ...] ). 您在列表推导( [x for x in ...] )内有一个生成器表达式(x for x in ...) )。 This will return a list of generator objects. 这将返回生成器对象列表。 Change the code like so 像这样更改代码

a = [['1','3','2'],['11','22','33']]
k = [[float(a[i][j]) for j in range(0,3)] for i in range(0,2)]

print(k)
# [[1.0, 3.0, 2.0], [11.0, 22.0, 33.0]]

You are using a generator expression in your list comprehension expression: 您在列表理解表达式中使用了生成器表达式:

(float(a[i][j]) for j in range(0,3))

If you wanted that to execute like a list comprehension, make that a list comprehension too : 如果你想要一个执行像列表解析,使列表理解

[[float(a[i][j]) for j in range(3)] for i in range(2)]

If you need those to be tuples, then you'll have to explicitly call tuple() : 如果您需要将它们作为元组,则必须显式调用tuple()

[tuple(float(a[i][j]) for j in range(3)) for i in range(2)]

The tuple() callable will drive the generator expression to produce a tuple of those values. 可调用的tuple()将驱动生成器表达式生成这些值的元组。 There is no such thing as a tuple comprehension , otherwise. 否则就没有元组理解这样的东西

Rather than use ranges, you can loop over a and the nested lists directly : 而不是使用范围,你可以遍历a 直接的嵌套列表:

[tuple(float(v) for v in nested) for nested in a]

Demo: 演示:

>>> a=[['1','3','2'],['11','22','33']]
>>> [tuple(float(v) for v in nested) for nested in a]
[(1.0, 3.0, 2.0), (11.0, 22.0, 33.0)]

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

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