# 重复列表的元素n次

##### 问题描述投票：35回答：8

``````x=[1,2,3,4]
n=3

x1=[1,1,1,2,2,2,3,3,3,4,4,4]
``````

`x*n`不起作用

``````for i in x[i]
x1=n*x[i]
``````

python
##### 8个回答
27

``````import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))

Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
``````

71

``````In [16]:

x1=[1,2,3,4]
In [17]:

np.repeat(x1,3)
Out[17]:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
``````

24

``````[item for item in x for i in range(n)]
``````

``````>>> x=[1, 2, 3, 4]
>>> n = 3
>>> new = [item for item in x for i in range(n)]
>>> new
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
>>>
``````

6

``````>>> [i for i in range(10) for _ in xrange(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]
``````

``````>>> x = [1, 2, 3, 4]
>>> n = 3
>>> [i for i in x for _ in xrange(n)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
``````

1

``````import itertools

def expand(lst, n):
lst = [[i]*n for i in lst]
lst = list(itertools.chain.from_iterable(lst))
return lst

x=[1,2,3,4]
n=3
x1 = expand(x,3)

print(x1)
``````

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

1

``````>>> x = [1,2,3,4]
>>> n = 3
>>> a = sorted(x*n)
>>> a
>>> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
``````

0

``````>>> ls = [1, 2, 3]
>>> ls[0: 0+1]
[1]
>>> ls[0: 0+1] = [4, 5, 6]
>>> ls
>>> [4, 5, 6, 2, 3]
``````
``````def repeat_elements(ls, times):
for i in range(len(ls) - 1, -1, -1):
ls[i: i+1] = [ls[i]] * times
``````

``````>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> repeat_elements(b, 3)
>>> b
[1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> a
[1, 1, 1, 2, 2, 2, 3, 3, 3]
``````

（如果你不想在原地修改它，你可以复制列表并返回副本，这不会修改原文。这也适用于其他序列，如`tuple`s，但不像`itertools.chain.from_iterable`那样懒惰和`itertools.repeat`方法）

``````def repeat_elements(ls, times):
ls = list(ls)  # Makes a copy
for i in range(len(ls) - 1, -1, -1):
ls[i: i+1] = [ls[i]] * times
return ls
``````

0

``````zAxe=[]
for i in range(5):
zAxe0 =[i] * 3
zAxe +=(zAxe0) # append allows accimulation of data
``````