开发者

Using list comprehension in Python to do something similar to zip()?

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 ap开发者_C百科propriate in this situation, but I'm just trying to understand lists a bit better). Thanks!


Something like this:

[[c, a] for c, a in zip(cities, airports)]

Alternately, the list constructor can convert tuples to lists:

[list(x) for x in zip(cities, airports)]

Or, the map function is slightly less verbose in this case:

map(list, zip(cities, airports))


If you wanted to do it without using zip at all, you would have to do something like this:

[ [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.


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.


This takes zip's output and converts all tuples to lists:

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


Possible to use enumerate, as well:

[[y,airports[x]] for x,y in enumerate(cities)]


If you wanted to use list comprehension, and create a variable as a dictionary here is a decent way to do it:

newvariable = {key: value for key, value in zip(cities,airports)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜