Possible to return two lists from a list comprehen

2019-01-23 01:41发布

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

3条回答
等我变得足够好
2楼-- · 2019-01-23 02:01

According to my tests, creating two comprehensions list wins (at least for long lists). Be aware that, the best voted answer is slower even slower than 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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-23 02:09
>>> rr,tt = zip(*[(i*10, i*12) for i in xrange(4)])
>>> rr
(0, 10, 20, 30)
>>> tt
(0, 12, 24, 36)
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-23 02:21

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.

查看更多
登录 后发表回答