list comprehension按元素值重复列表中的元素

时间:2014-08-06 09:28:58

标签: python list-comprehension python-3.3

我无法弄清楚要执行此操作的代码,有类似的帖子:Repeating elements in list comprehension

但我想按列表中的值重复列表中的值

In [219]:

l = [3,1]

[i for x in range(i) for i in l]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-219-84d6f25dfd96> in <module>()
      1 l = [3,1]
      2 
----> 3 [i for x in range(i) for i in l]

TypeError: 'tuple' object cannot be interpreted as an integer

我想要的是这样的列表:

[3,3,3,1]

也可以有人解释错误。

注意我在这里运行python 3.3

2 个答案:

答案 0 :(得分:3)

[x for x in l for _ in range(x)]
# Out[5]: [3, 3, 3, 1]

但是我更喜欢来自itertools的更冗长,更直接(字面)的函数:

from itertools import chain, repeat
list(chain.from_iterable(repeat(x, x) for x in l))

答案 1 :(得分:0)

又一种解决方案。

l = [3,1]

ll = reduce(lambda a, b: a + [b] * b, l, [])

print ll