在Python中使用列表理解来执行类似于zip()的操作? [英] Using list comprehension in Python to do something similar to zip()?
问题描述
我是一名Python新手,我想做的一件事就是将自己的头放在列表理解上.我看到它是一个非常强大的功能,值得学习.
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!
推荐答案
类似以下内容:
[[c, a] for c, a in zip(cities, airports)]
或者,list
构造函数可以将元组转换为列表:
Alternately, the list
constructor can convert tuples to lists:
[list(x) for x in zip(cities, airports)]
或者,在这种情况下,map
函数的详细程度略有降低:
Or, the map
function is slightly less verbose in this case:
map(list, zip(cities, airports))
这篇关于在Python中使用列表理解来执行类似于zip()的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!