简体   繁体   English

为什么对 zip() 调用的列表理解返回包含 zip object 的列表,而不是 zip() 的返回值列表?

[英]Why does a list comprehension over a zip() call return a list containing the zip object instead of a list of zip()'s return values?

Playing around with python3 REPL and noticed the following:使用 python3 REPL 并注意到以下内容:

Why are print( [zip([1,2,3], [3,1,4])] ) and print( list(zip([1,2,3], [3,1,4])) ) different?为什么是print( [zip([1,2,3], [3,1,4])] )print( list(zip([1,2,3], [3,1,4])) )不同的?

The first returns [<zip object at 0xblah>] and the second returns [(1,3), (2,1), (3,4)] .第一个返回[<zip object at 0xblah>] ,第二个返回[(1,3), (2,1), (3,4)]

Trying to understand why the list comprehension in the first statement doesn't give me the result that the list() constructor gives - I think I'm confused about the difference between list comprehension and list() and would appreciate insight into what's happening under the hood.试图理解为什么第一个语句中的列表理解没有给我list()构造函数给出的结果 - 我想我对列表理解和list()之间的区别感到困惑,并希望深入了解下面发生的事情引擎盖。

Searching gives me this question on lists and tuples which doesn't answer my question.搜索给了我这个关于列表和元组的问题,它没有回答我的问题。

Edit: A suggested question on The zip() function in Python 3 is very helpful background, but does not address the confusion in my question about the difference between a list comprehension and a list literal, so i prefer the submitted answer below as more complete.编辑:关于Python 3 中的 zip() function的建议问题是非常有用的背景,但没有解决我的问题中关于列表理解列表文字之间差异的混淆,所以我更喜欢下面提交的答案更完整.

The first statement is not a list comprehension, a list comprehension would give you the same result.第一条语句不是列表推导,列表推导会给您相同的结果。 It is just a list literal containing a zip object:它只是一个包含 zip object 的列表文字:

This would be a list comprehension:这将是一个列表理解:

[value for value in zip([1,2,3], [3,1,4])]

The above will print the same as list(zip([1, 2, 3], [3, 1, 4])) .上面将打印与list(zip([1, 2, 3], [3, 1, 4]))相同的内容。


In general, [something] means: A list with one element: something .一般来说, [something]意味着:一个包含一个元素的列表: something

On the other hand, list(something) means: Iterate over the values in something, and make a list from the result.另一方面, list(something)意味着:迭代某事物中的值,并从结果中创建一个列表。 You can see the difference for example by putting primitive objects inside it, like a number:例如,您可以通过将原始对象放入其中来查看差异,例如数字:

>>> [2]
[2]
>>> list(2)
TypeError: 'int' object is not iterable

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

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