Python 重复列表中的元素n次
如何将列表中的每个元素重复Python 重复列表中的元素n次,python,Python,如何将列表中的每个元素重复n次并形成一个新列表?例如: x = [1,2,3,4] n = 3 x1 = [1,1,1,2,2,2,3,3,3,4,4,4] >>> 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] x*n不起作用 for i in x[i]: x1 = n *
n
次并形成一个新列表?例如:
x = [1,2,3,4]
n = 3
x1 = [1,1,1,2,2,2,3,3,3,4,4,4]
>>> 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]
x*n
不起作用
for i in x[i]:
x1 = n * x[i]
必须有一个简单而智能的方法。嵌套列表comp在这里工作:
>>> [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
x1 = [1,1,1,2,2,2,3,3,3,4,4,4]
>>> 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, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
说明:
这样做,
[3]*3
给出了[3,3,3]
的结果,用n
替换它,我们得到[3,3,3,…3](n次)
使用列表理解,我们可以遍历列表的每个元素并执行此操作,最后我们需要展平列表,我们可以通过列表(itertools.chain.from_iterable(lst))来完成此操作
您可以使用列表理解:
[item for item in x for i in range(n)]
理想的方法可能是
numpy。重复:
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])
如果您确实希望结果作为列表,并且生成器不够:
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]
如果您想就地修改列表,最好的方法是从后面迭代,并将以前一个项目的一部分分配给该项目的列表n
次
这是因为切片分配:
>>> ls = [1, 2, 3]
>>> ls[0: 0+1]
[1]
>>> ls[0: 0+1] = [4, 5, 6]
>>> ls
>>> [4, 5, 6, 2, 3]
演示用途:
>>> 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
方法那样懒惰)
一种更简单的方法是将列表x
与n
相乘,并对结果列表进行排序。e、 g
>>> x = [1,2,3,4]
>>> n = 3
>>> a = sorted(x*n)
>>> a
>>> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
对于基本Python 2.7:
from itertools import repeat
def expandGrid(**kwargs):
# Input is a series of lists as named arguments
# output is a dictionary defining each combination, preserving names
#
# lengths of each input list
listLens = [len(e) for e in kwargs.itervalues()]
# multiply all list lengths together to get total number of combinations
nCombos = reduce((lambda x, y: x * y), listLens)
iDict = {}
nTimesRepEachValue=1 #initialize as repeating only once
for key in kwargs.keys():
nTimesRepList=nCombos/(len(kwargs[key])*nTimesRepEachValue)
tempVals=[] #temporary list to store repeated
for v in range(nTimesRepList):
indicesToAdd=reduce((lambda x,y: list(x)+list(y)),[repeat(x, nTimesRepEachValue) for x in kwargs[key]])
tempVals=tempVals+indicesToAdd
iDict[key] = tempVals
# Accumulating the number of times needed to repeat each value
nTimesRepEachValue=len(kwargs[key])*nTimesRepEachValue
return iDict
#Example usage:
expandedDict=expandGrid(letters=["a","b","c","d"],nums=[1,2,3],both=["v",3])
方式1:
def foo():
对于[1,3,2]中的j:
[j]*5的收益率
方式2:
来自itertools导入链的
l=[3,1,2]
链条(*拉链(*[l]*3))
方式3:
sum([i]*5表示[2,1,3]中的i),[])
这将解决您的问题:
x=[1,2,3,4]
n = 3
x = sorted(x * n)
itertools.chain(*x)
现在应该写成itertools.chain.from\u iterable(x)
没问题。我经常看到这种情况。前者的问题是,它通过解包操作符的优点将iterable解析为元组,这部分克服了itertools
.pandas.Index.的奇妙惰性。只需重复一次对np的调用。repeat@AndyHayden,但是OP标记了我看到了,但是pandas.Index.repeat
是np.repeat(作为一种ndarray方法),这里没有熊猫的魔力,为了它而叫熊猫似乎很愚蠢(特别是当它不是索引的时候!)。最好只做np.array([1,2,3,4])。重复(3)
。我不知道这个问题与熊猫tbh有什么特别的关系(我看到你已经删除/回滚了一个标记编辑)…@我第一次删除它是因为我认为它与此无关。但是现在,我看到OP可能想用解决它。对我来说,这非常有效,因为我还想在乘法后对列表进行排序。如果要保留顺序,则不会起作用。x=list('NESW')
。相关问题:,。另外:对于那些对效率感兴趣的人来说,这是一个(如果不是)这篇文章列出了最快的方法。检查我的答案@S3DEVThanks了解这个技巧zAxe+=(zAxe0)#append允许数据模拟
。
zAxe=[]
for i in range(5):
zAxe0 =[i] * 3
zAxe +=(zAxe0) # append allows accimulation of data
from itertools import repeat
def expandGrid(**kwargs):
# Input is a series of lists as named arguments
# output is a dictionary defining each combination, preserving names
#
# lengths of each input list
listLens = [len(e) for e in kwargs.itervalues()]
# multiply all list lengths together to get total number of combinations
nCombos = reduce((lambda x, y: x * y), listLens)
iDict = {}
nTimesRepEachValue=1 #initialize as repeating only once
for key in kwargs.keys():
nTimesRepList=nCombos/(len(kwargs[key])*nTimesRepEachValue)
tempVals=[] #temporary list to store repeated
for v in range(nTimesRepList):
indicesToAdd=reduce((lambda x,y: list(x)+list(y)),[repeat(x, nTimesRepEachValue) for x in kwargs[key]])
tempVals=tempVals+indicesToAdd
iDict[key] = tempVals
# Accumulating the number of times needed to repeat each value
nTimesRepEachValue=len(kwargs[key])*nTimesRepEachValue
return iDict
#Example usage:
expandedDict=expandGrid(letters=["a","b","c","d"],nums=[1,2,3],both=["v",3])
[myList[i//n] for i in range(n*len(myList))]
x=[1,2,3,4]
n = 3
x = sorted(x * n)