3

假设我有这个列表:

[1,2,3,4]

而且我要:

[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]

这样做的最佳方法是什么?

我目前的方法是创建一个新列表:

x = [1,2,3,4]
y = [[n]*4 for n in x]

这给出了:

[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]

这似乎很接近,但没有雪茄......有人可以帮忙吗?

4

5 回答 5

13
>>> 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确实在语义上更干净,谢谢,史蒂文:

from itertools import repeat
[repeated for value in x for repeated in repeat(value, 4)]
于 2013-03-14T15:09:14.313 回答
2

您可以使用itertools.chain()chain.from_iterable()展平列表列表(y在您的情况下):

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]

一些性能比较:

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
于 2013-03-14T15:09:37.690 回答
1

您可以随时使用reduce

reduce(lambda x, y: x+y, [[n]*4 for n in x])
于 2013-03-14T15:17:21.900 回答
1

这就是我会怎么做。

x = [1,2,3,4]
y = x*4
y.sort()

简单而整洁。

于 2016-12-23T20:10:38.003 回答
0

简易方法:

y = [n for n in x*4]

这将返回[1, 2, 3, 4, 1, 2, 3, 4, ...]

要将其按您想要的顺序排列,您可以执行x = sorted(x)or y = sorted([n for n in x*4])

这类似于y = sorted(x*4).

最好的方法是按照@Pavel Anossov 的说法去做:

y = [n for n in x for _ in range(4)]

这是最好的,因为它适用于任何序列,sorted(x*4)但不保持顺序,只适用于最初排序的列表。

于 2013-03-14T15:08:56.140 回答