Possible to return two lists from a list comprehension?

Is it possible to return two lists from a list comprehension? Well, this obviously doesn't work, but something like:

rr, tt = [i*10, i*12 for i in xrange(4)]

So rr and tt both are lists with the results from i*10 and i*12 respectively. Many thanks


>>> rr,tt = zip(*[(i*10, i*12) for i in xrange(4)])
>>> rr
(0, 10, 20, 30)
>>> tt
(0, 12, 24, 36)

It is possible for a list comprehension to return multiple lists if the elements are lists. So for example:

>>> x, y = [[] for x in range(2)]
>>> x
[]
>>> y
[]
>>>

The trick with zip function would do the job, but actually is much more simpler and readable if you just collect the results in lists with a loop.


According to my tests, creating two comprehensions list wins (at least for long lists). Be aware that, the best voted answer is slower even than the traditional for loops. List comprehensions are faster and clearer .

python -m timeit -n 100 -s 'rr=[];tt = [];' 'for i in range(500000): rr.append(i*10);tt.append(i*12)' 
10 loops, best of 3: 123 msec per loop

> python -m timeit -n 100 rr,tt = zip(*[(i*10, i*12) for i in range(500000)])' 
10 loops, best of 3: 170 msec per loop

> python -m timeit -n 100 'rr = [i*10 for i in range(500000)]; tt = [i*10 for i in range(500000)]' 
10 loops, best of 3: 68.5 msec per loop

It would be nice to see comprehension lists supporting the creation of multiple lists at a time.

链接地址: http://www.djcxy.com/p/53586.html

上一篇: 比较两个元组的所有元素(具有all()功能)

下一篇: 可以从列表理解返回两个列表?