在 Python 中使用列表理解来执行类似于 zip() 的操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2169623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using list comprehension in Python to do something similar to zip()?
提问by jamieb
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.
我是 Python 新手,我正在尝试做的一件事就是围绕列表理解进行思考。我可以看到这是一个非常强大的功能,值得学习。
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!
(我意识到在这种情况下字典可能更合适,但我只是想更好地理解列表)。谢谢!
回答by Greg Hewgill
Something like this:
像这样的东西:
[[c, a] for c, a in zip(cities, airports)]
Alternately, the list
constructor can convert tuples to lists:
或者,list
构造函数可以将元组转换为列表:
[list(x) for x in zip(cities, airports)]
Or, the map
function is slightly less verbose in this case:
或者,map
在这种情况下,该函数稍微不那么冗长:
map(list, zip(cities, airports))
回答by Dave Kirby
If you wanted to do it without using zip at all, you would have to do something like this:
如果您想在不使用 zip 的情况下完成此操作,则必须执行以下操作:
[ [cities[i],airports[i]] for i in xrange(min(len(cities), len(airports))) ]
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.
使用map(list, zip(cities, airports))
更短、更简单并且几乎肯定会运行得更快。
回答by Alex Martelli
A list comprehension, without some help from zip
, map
, or itertools
, cannot institute a "parallel loop" on multiple sequences -- only simple loops on one sequence, or "nested" loops on multiple ones.
没有来自zip
,map
或 的帮助的列表推导式itertools
无法在多个序列上建立“并行循环”——只有一个序列上的简单循环,或多个序列上的“嵌套”循环。
回答by Wim
This takes zip
's output and converts all tuples to lists:
这需要zip
的输出并将所有元组转换为列表:
map(list, zip(cities, airports))
As for the performance of each:
至于每个人的表现:
$ python -m timeit -c '[ [a, b] for a, b in zip(xrange(100), xrange(100)) ]'
10000 loops, best of 3: 68.3 usec per loop
$ python -m timeit -c 'map(list, zip(xrange(100), xrange(100)))'
10000 loops, best of 3: 75.4 usec per loop
$ python -m timeit -c '[ list(x) for x in zip(range(100), range(100)) ]'
10000 loops, best of 3: 99.9 usec per loop
回答by ohmydog
Possible to use enumerate
, as well:
也可以使用enumerate
:
[[y,airports[x]] for x,y in enumerate(cities)]