如何在列表python中复制值

时间:2015-02-14 01:36:23

标签: python

快速提问...搜索到并没有找到任何结果。我有这个清单:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

我希望每个值在同一个列表中重复3次...我该怎么办?我尝试了一些for循环.append到列表但事情变得混乱。我最终得到列表中的列表中的一些列表。我有一种感觉.append不适合这种情况。

5 个答案:

答案 0 :(得分:4)

In [1]: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

In [2]: sorted(my_list * 3)

请注意,您不应将list用作变量名称,因为它会影响关键字list

另一个选择是使用numpy

In [8]: import numpy as np

In [9]: np.repeat(my_list, 3)

答案 1 :(得分:2)

在列表推导中使用嵌套循环。

>>> [x for x in L for y in range(4)]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

答案 2 :(得分:1)

你可以尝试这样的事情!

baselist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
[z for y in [[x]*4 for x in baselist] for z in y]

这相当于:

listofLists = []
for x in baseList:
    listofLists.append([x]*4)

finalList = []
for y in listofLists:
    for z in y:
        finalList.append(z)

你知道,列表理解只是缩短了逻辑,但它是否更具可读性将取决于你对理解语法的掌握。

答案 3 :(得分:1)

你可以这样做,

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
>>> [j for i in lst for j in [i,i,i,i]]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

答案 4 :(得分:0)

使用flatten recipe

的另一个itertools变体
>>> m = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
>>> import itertools
>>> list(itertools.chain.from_iterable(itertools.izip(m,m,m,m)))
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>>