在 Python 中使用列表理解来执行类似于 zip() 的操作?
我是一名 Python 新手,我想做的一件事就是围绕列表理解进行思考。我可以看到这是一个非常强大的功能,值得学习。
cities = ['Chicago', 'Detroit', 'Atlanta']
airports = ['ORD', 'DTW', 'ATL']
print zip(cities,airports)
[('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')]
如何使用列表理解,以便可以将结果作为列表中的一系列列表而不是列表中的一系列元组来获取?
[['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']]
(我意识到字典在这种情况下可能更合适,但我只是想更好地理解列表)。谢谢!
I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it's a pretty powerful feature that's worth learning.
cities = ['Chicago', 'Detroit', 'Atlanta']
airports = ['ORD', 'DTW', 'ATL']
print zip(cities,airports)
[('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')]
How do I use list comprehension so I can get the results as a series of lists within a list, rather than a series of tuples within a list?
[['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']]
(I realize that dictionaries would probably be more appropriate in this situation, but I'm just trying to understand lists a bit better). Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
像这样的东西:
或者,
list
构造函数可以将元组转换为列表:或者,在这种情况下,
map
函数稍微不那么冗长:Something like this:
Alternately, the
list
constructor can convert tuples to lists:Or, the
map
function is slightly less verbose in this case:如果您想完全不使用 zip 来完成此操作,则必须执行以下操作:
但除了智力练习之外,没有理由这样做。
使用
map(list, zip(cities, airports))
更短、更简单,而且几乎肯定会运行得更快。If you wanted to do it without using zip at all, you would have to do something like this:
but there is no reason to do that other than an intellectual exercise.
Using
map(list, zip(cities, airports))
is shorter, simpler and will almost certainly run faster.如果没有
zip
、map
或itertools
的帮助,列表理解无法在多个序列上建立“并行循环”——只能是简单的在一个序列上循环,或在多个序列上“嵌套”循环。A list comprehension, without some help from
zip
,map
, oritertools
, cannot institute a "parallel loop" on multiple sequences -- only simple loops on one sequence, or "nested" loops on multiple ones.这需要 zip 的输出并将所有元组转换为列表:
至于每个元组的性能:
This takes
zip
's output and converts all tuples to lists:As for the performance of each:
也可以使用
enumerate
:Possible to use
enumerate
, as well:如果您想使用列表理解,并创建一个变量作为字典,这里是一个不错的方法:
If you wanted to use list comprehension, and create a variable as a dictionary here is a decent way to do it:
您可以使用列表理解来组合两个列表,但在现实世界中,您应该更喜欢内置函数 (zip()) 而不是复杂的流语句。
You can use list comprehension to combine two lists,however in the real world you should prefer builtin functions (zip()) to complex flow statements.