3

我有这样的事情:

[e for e in ([n for n in xrange(random.randrange(1, 5))] for x in xrange(10))]

它产生:

[[0, 1, 2, 3], [0, 1, 2], [0], [0], [0, 1], [0], [0, 1], [0, 1, 2, 3], [0, 1, 2], [0, 1, 2]]

我需要同样的但扁平的结构。

现在我使用类似的东西:

l = []
[l.extend(e) for e in ([n for n in xrange(random.randrange(1, 5))] for x in xrange(10))]

但是,在理解中实现这种任意长度列表的“解包”是否有一些不那么晦涩的东西?

4

4 回答 4

7

使用此列表理解:

In [8]: [y for x in xrange(10) for y in xrange(random.randrange(1, 5))]
Out[8]: [0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 3, 0, 0, 1, 0]

上面的列表理解等价于这个(但 LC 更快):

In [9]: lis=[]

In [10]: for x in xrange(10):
   ....:     for y in xrange(random.randrange(1, 5)):
   ....:         lis.append(y)
   ....:         
于 2013-04-07T13:38:17.023 回答
3

在一般情况下展平任何可迭代的最佳方法是itertools.chain.from_iterable()

>>> import random
>>> from itertools import chain
>>> x = [e for e in ([n for n in xrange(random.randrange(1, 5))] 
...      for x in xrange(10))]
>>> list(chain.from_iterable(x))
[0, 0, 0, 1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 1, 0, 1, 0, 0, 1, 2]

这就是说,最好避免在这种情况下的额外工作,只需.

于 2013-04-07T13:38:08.717 回答
3

您可以使用numpy flatten()

import numpy as np
l = [e for e in ([n for n in xrange(random.randrange(1, 5))] for x in xrange(10))]
a = np.asarray(l)
l = list(a.flatten(l))
print l
于 2013-04-07T13:38:24.283 回答
0
import itertools
l = [e for e in ([n for n in xrange(random.randrange(1, 5))] for x in xrange(10))]
result = list(itertools.chain(*l))

然后print result给出:

[0,1,2,3,0,1,2,0...]

*in chain(*l) 的使用灵感来自这个问题join list of lists in python

于 2013-04-07T13:45:12.413 回答