[英]Duplicating elements in a list x number of times
I want to duplicate each element individually right after each other while preserving the order. 我想在保留订单的同时将每个元素一个接一个地复制。 For example the function would look like 例如,函数看起来像
def duplicate(testList, n)
for i in l:
ll.append(i)
ll.append(i)
testList
being the input list and n
being the number of times you duplicate each element within. testList
是输入列表, n
是你复制每个元素的次数。 With what I came up with I can't loop it for a certain number of times. 根据我的想法,我无法将其循环一定次数。 Not sure how to do it. 不知道怎么做。
how bout 怎么样
def n_times(v,n):
for i in range(n):
yield v
[i for j in testList for i in n_times(j,2)]
You can simply add second loop which will iterate n times adding your values. 您可以简单地添加第二个循环,它将迭代n次添加您的值。 However I advice you to learn generators as well and do it on one line like Joran Beasley suggested. 不过,我建议你学习发电机,并像Joran Beasley建议的那样在一条线上完成。
def duplicate(testList, n)
for i in l:
for x in range(n):
ll.append(i)
If your are looking for a result like Ashwini Chaudhary described , you can go like this: 如果您正在寻找像Ashwini Chaudhary所描述的结果,您可以这样:
from itertools import chain # Hinted by Ashwini Chaudhary
def repeat(lst, n):
return list(chain(*zip(*[x for _ in range(n)])))
>>> repeat([1, 2, 3], 3)
[1, 1, 1, 2, 2, 2, 3, 3, 3]
Otherwise, if you are looking for just repeating the list n
times, as a general solution you could go with the following function: 否则,如果您正在寻找仅重复列表n
次,作为一般解决方案,您可以使用以下函数:
def repeat(lst, n):
result = []
for _ in range(n):
result += lst[:]
return result
>>> repeat([1, 2, 3], 2)
[1, 2, 3, 1, 2, 3]
However, if the elements are guaranteed to be immutable objects , there is a pretty nice way for a list to do that in Python: 但是, 如果元素保证是不可变对象 ,那么列表在Python中有一个非常好的方法:
>>> [1, 2, 3] * 2
[1, 2, 3, 1, 2, 3]
As a one-liner: 作为单线:
def n_plicate(testList, n):
return reduce(lambda x,y: x+y, map(lambda x: [x]*n, testList))
or a little bit easier to read and faster: 或者更容易阅读和更快:
return [tm for sblst in [[x]*n for x in testList] for tm in sblst]
Long and Easier, without any imports, 长而容易,没有任何进口,
def duplicate(listt,number):
"""Input a list and a num evry vlue in the list is replctd by Num of times """
temp=[]
for i in listt:
temp.append(i*number)
output=[]
for j in temp:
output.extend(list(j))
return output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.