【问题标题】:How to replicate a list to the length of list2?如何将列表复制到 list2 的长度?
【发布时间】:2019-03-24 23:19:47
【问题描述】:

我有一定长度的 list1 和一定长度的 list2。比方说:

list1 = [32, 345, 76, 54]

list2 = [43, 65, 76, 23, 12, 23, 44]

我需要让 list1 循环,直到它与 list2 的长度相同。或者,如果 list1 更长,我需要将它缩减到 list2 的长度。对于上面的例子,我正在寻找:

list1 = [32, 345, 76, 54, 32, 345, 76]

不一定要保留list1。它可以是一个新列表,我只需要 list1 中的相同值循环回一定次数。我该怎么做呢?我对 python 还很陌生,我还没有找到任何有用的东西。

【问题讨论】:

    标签: python list iterator


    【解决方案1】:

    了解精彩的itertools 模块!

    from itertools import cycle, islice
    
    result = list(islice(cycle(list1), len(list2)))
    

    如果您只需要“一起”迭代这两个列表,那就更容易了:

    for x, y in zip(cycle(list1), list2):
        print(x, y)
    

    【讨论】:

      【解决方案2】:

      使用itertools.cycle:

      from itertools import cycle
      
      new_list1 = [element for element, index in zip(cycle(list1), range(len(list2)))]
      new_list1
      

      输出:

      [32, 345, 76, 54, 32, 345, 76]
      

      【讨论】:

      • 为什么是index?如果是这样,为什么不enumerate
      • 因为zip 将在传递给它的最短的可迭代对象用尽时停止产生值。不过islice 更好。
      【解决方案3】:

      这是一个使用itertools.cycle 的更详细解决方案,其他人已经演示过。这种方式可能更容易理解。

      target = len(list2) # the target length we want to hit
      curr = 0 # keep track of the current length of output
      out = [] # our output list
      inf = cycle(list1) # an infinite generator that yields values
      
      while curr < target:
          out.append(next(inf))
          curr += 1
      
      print(out)
      # [32, 345, 76, 54, 32, 345, 76]
      

      【讨论】:

        【解决方案4】:

        你可以用纯 Python 做到这一点:

        list1 = [32, 345, 76, 54]
        
        list2 = [43, 65, 76, 23, 12, 23, 44]
        
        l1, l2 = (len(list1) ,len(list2)) 
        diff = (l2- l1) % l2
        times = (l2 - l1) // l2
        list1 = list1 * (times+1) + list1[:diff]
        print(list1)
        

        结果:

        [32, 345, 76, 54, 32, 345, 76]
        

        另一种选择是:

        list1 = [32, 345, 76, 54]
        
        list2 = [43, 65, 76, 23, 12, 23, 44]
        
        times = len(list1) + (len(list2) - len(list1))
        list1 = [list1[i%len(list1)] for i in range(times)]
        print(list1)
        

        【讨论】:

          猜你喜欢
          • 2012-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多