【问题标题】:Repeating elements of a list n times将列表的元素重复 n 次
【发布时间】:2014-08-05 04:17:55
【问题描述】:

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

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


【解决方案1】:

嵌套列表组合在这里工作:

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

【讨论】:

    【解决方案2】:
    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]
    

    解释:

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

    【讨论】:

    • itertools.chain(*x) 这些天应该写成itertools.chain.from_iterable(x)
    • 没问题。我比较频繁地看到那个。前者的问题在于,它通过解包运算符的优点将您的可迭代对象解析为一个元组,这部分克服了itertools 的奇妙懒惰。
    【解决方案3】:

    您可以使用列表推导:

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

    【讨论】:

    • pandas.Index.repeat 只是调用 np.repeat
    • @AndyHayden,但 OP 标记为 pandas
    • 我明白了,但是pandas.Index.repeat is np.repeat(作为 ndarray 方法),这里没有 pandas 的魔法,为了起见而调用 pandas 似乎很愚蠢(尤其是当它不是索引时!)。最好只做np.array([1, 2, 3, 4]).repeat(3)
    • 我的问题与 pandas tbh 没有任何特别的关系(我看到您已经删除/回滚了标签编辑)...
    • @AndyHayden 我第一次删除它是因为我认为它无关紧要。但现在,我看到 OP 可能想pandas 解决它。
    【解决方案4】:

    理想的方式大概是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])
    

    【讨论】:

      【解决方案5】:

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

      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]
      

      【讨论】:

      • 对于那些对效率感兴趣的人,这是本文中列出的(如果不是 the最快的方法之一。
      • 检查我的答案@S3DEV
      【解决方案6】:

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

      这是由于切片分配而起作用的:

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

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

      【讨论】:

        【解决方案7】:

        实现此目的的更简单方法是将列表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]
        

        【讨论】:

        • 对我来说这很完美,因为我还想在乘法之后对列表进行排序。
        • 如果要保留订单将不起作用x = list('NESW')
        【解决方案8】:
        zAxe=[]
        for i in range(5):
            zAxe0 =[i] * 3
            zAxe +=(zAxe0) # append allows accimulation of data 
        

        【讨论】:

        • 感谢这个技巧; zAxe +=(zAxe0) # append allows accimulation of data
        【解决方案9】:

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

        【讨论】:

          【解决方案10】:
           [myList[i//n] for i in range(n*len(myList))]
          

          【讨论】:

            【解决方案11】:

            方式一:

            def foo():
                for j in [1, 3, 2]:
                    yield from [j]*5
            

            方式2:

            from itertools import chain
            l= [3, 1, 2]
            chain(*zip(*[l]*3))
            

            方式 3:

            sum(([i]*5 for i in [2, 1, 3]), [])
            

            【讨论】:

              【解决方案12】:

              这将解决您的问题:

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

              【讨论】:

              • 欢迎访问该站点,但您的解决方案与existing one 相同。
              • 此解决方案无法用于未排序的列表。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-03-11
              • 2020-11-19
              • 2018-01-29
              • 1970-01-01
              • 1970-01-01
              • 2016-01-07
              • 2018-08-11
              相关资源
              最近更新 更多