Python 重复列表的元素 n 次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24225072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:15:45  来源:igfitidea点击:

Repeating elements of a list n times

python

提问by user3720101

How do I repeat each element of a list ntimes and form a new list? For example:

如何重复列表中的每个元素n并形成一个新列表?例如:

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

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

x*ndoesn't work

x*n不起作用

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

There must be a simple and smart way.

必须有一个简单而聪明的方法。

采纳答案by m.wasowski

In case you really want result as list, and generator is not sufficient:

如果你真的想要结果作为列表,而生成器是不够的:

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]

回答by mgilson

A nested list-comp works here:

一个嵌套的 list-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]

Or to use your example:

或者使用您的示例:

>>> 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]

回答by Dair

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)

Gives:

给出:

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

Explanation:

解释:

Doing, [3]*3gives the result of [3,3,3], replacing this with nwe get [3,3,3,...3] (n times)Using a list comprehension we can go through each elem of the list and perform this operation, finally we need to flatten the list, which we can do by list(itertools.chain.from_iterable(lst))

做,[3]*3给出的结果[3,3,3],用n我们得到的替换它[3,3,3,...3] (n times)使用列表推导式,我们可以遍历列表的每个元素并执行此操作,最后我们需要展平列表,我们可以通过list(itertools.chain.from_iterable(lst))

回答by A.J. Uppal

You can use list comprehension:

您可以使用列表理解:

[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)]
#[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

回答by CT Zhu

The ideal way is probably numpy.repeat:

理想的方式可能是numpy.repeat

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])

回答by Artyer

If you want to modify the list in-place, the best way is to iterate from the back and assign a slice of what was previously one item to a list of that item ntimes.

如果您想就地修改列表,最好的方法是从后面迭代并将之前一个项目的一部分分配给该项目n时间的列表。

This works because of slice assignment:

这是因为切片分配:

>>> 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

Demo usage:

演示用法:

>>> 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]

(If you don't want to modify it in-place, you can copy the list and return the copy, which won't modify the original. This would also work for other sequences, like tuples, but is not lazy like the itertools.chain.from_iterableand itertools.repeatmethod)

(如果你不想就地修改它,你可以复制列表并返回副本,这不会修改原始的。这也适用于其他序列,如tuples,但不像itertools.chain.from_iterableand那样懒惰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

回答by Sohaib Farooqi

A simpler way to achieve this to multiply the list xwith nand sort the resulting list. e.g.

实现此目的的一种更简单的方法是将列表xn结果列表相乘并对结果列表进行排序。例如

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

回答by Peyman Obeidy

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

回答by Ross

For base Python 2.7:

对于基础 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])