问题
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