list comprehension to repeat element in a list by element value

好久不见. 提交于 2019-12-20 07:44:20

问题


I can't quite figure out the code to do this, there are similar posts: Repeating elements in list comprehension

but I want to repeat a value in the list by the value in the list

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

What I want is a list like so:

[3,3,3,1]

Also can someone explain the error.

Note I am running python 3.3 here


回答1:


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

But I prefer more verbose, yet more straigforward (literal) functions from itertools:

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



回答2:


Yet another solution.

l = [3,1]

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

print ll


来源:https://stackoverflow.com/questions/25156745/list-comprehension-to-repeat-element-in-a-list-by-element-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!