简体   繁体   English

试图了解python中的以下生成器

[英]Trying to understand the following generator in python

I am trying to understand the difference between the following two code snippets. 我试图了解以下两个代码段之间的区别。 The second one just prints the generator but the first snippet expands it and iters the generator. 第二个只是打印生成器,而第一个片段将其扩展并迭代生成器。 Why does it happen? 为什么会发生? Is it because the two square brackets expand any iterable object? 是否因为两个方括号扩展了任何可迭代的对象?


#Code snippet 1


li=[[1,2,3],[4,5,6],[7,8,9]] 
for col in range(0,3):
    print( [row[col] for row in li] )`
Output: 
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

#Code snippet 2


li=[[1,2,3],[4,5,6],[7,8,9]]
for col in range(0,3):
    print( row[col] for row in li )

Output 产量

<generator object <genexpr> at 0x7f1e0aef55c8>
<generator object <genexpr> at 0x7f1e0aef55c8>
<generator object <genexpr> at 0x7f1e0aef55c8>

Why is the output of above two quotes different? 为什么以上两个引号的输出不同?

The print function outputs the returning values of the __str__ method of the objects in its arguments. print函数在其参数中输出对象的__str__方法的返回值。 For lists, the __str__ method returns a nicely formatted string of comma-delimited item values enclosed in square brackets, but for generator objects, the __str__ method simply returns generic object information so to avoid altering the state of the generator. 对于列表, __str__方法返回一个格式良好的字符串,用方括号括起来,以逗号分隔项目值,但是对于生成器对象, __str__方法仅返回通用对象信息,从而避免更改生成器的状态。

By putting a generator expression in square brackets you're using list comprehension to explicitly make a list by iterating through the output of the generator expression. 通过将生成器表达式放在方括号中,您将使用列表推导通过迭代生成器表达式的输出来显式创建列表。 Since the items are already produced, the __str__ method of the list would have no problem returning their values. 由于这些项目已经产生,因此列表的__str__方法将毫无问题地返回其值。

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

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