Reputation: 31040
Say I have this list:
[1,2,3,4]
and I want:
[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]
What is the best way of doing this?
My current method is to create a new list:
x = [1,2,3,4]
y = [[n]*4 for n in x]
This gives:
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
Which seems close but no cigar... Can anyone help?
Upvotes: 3
Views: 5312
Reputation: 11
Here is how I would have done.
x = [1,2,3,4]
y = x*4
y.sort()
Easy and Neat.
Upvotes: 1
Reputation: 250931
You can use itertools.chain()
or chain.from_iterable()
to flatten a list of lists (y
in your case) :
In [23]: lis=[1,2,3,4]
In [24]: from itertools import chain
In [31]: y = list(chain(*([n]*4 for n in lis)))
In [32]: y
Out[32]: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
Some performance comparisons:
In [25]: x=[1,2,3,4]*1000 #can't use more than 1000 due to limited RAM
In [26]: %timeit list(chain(*([n]*1000 for n in x)))
1 loops, best of 3: 196 ms per loop
In [27]: %timeit list(chain.from_iterable(([n]*1000 for n in x)))
1 loops, best of 3: 177 ms per loop
In [29]: %timeit [n for n in x for _ in xrange(1000)]
1 loops, best of 3: 388 ms per loop
#three more solutions;from @Steven Rumbalski
In [28]: %timeit [repeated for value in x for repeated in repeat(value,1000)]
1 loops, best of 3: 344 ms per loop
In [30]: %timeit list(chain.from_iterable(izip(*repeat(x,1000))))
1 loops, best of 3: 204 ms per loop
In [31]: %timeit list(chain(*izip(*repeat(x,1000))))
1 loops, best of 3: 238 ms per loop
Upvotes: 2
Reputation: 62908
>>> x = [1,2,3,4]
>>> [n for n in x for _ in range(4)]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
itertools.repeat
is indeed semantically cleaner, thanks, Steven:
from itertools import repeat
[repeated for value in x for repeated in repeat(value, 4)]
Upvotes: 13
Reputation: 685
You can always use reduce
reduce(lambda x, y: x+y, [[n]*4 for n in x])
Upvotes: 1
Reputation: 17532
Easy method:
y = [n for n in x*4]
This will return [1, 2, 3, 4, 1, 2, 3, 4, ...]
.
To put it in the order you wanted, you can do x = sorted(x)
or y = sorted([n for n in x*4])
.
This is similar to y = sorted(x*4)
.
The best method is to do it how @Pavel Anossov stated:
y = [n for n in x for _ in range(4)]
This is best because it will work for any sequence whereas sorted(x*4)
does not keep the order and only works for originally sorted lists.
Upvotes: 0