【问题标题】:How to zip two differently sized lists, repeating the shorter list?如何压缩两个不同大小的列表?
【发布时间】:2013-11-10 06:42:06
【问题描述】:

我想压缩两个不同长度的列表

例如

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

我期待这个

[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (5, 'B'), (6, 'C'), (7, 'A'), (8, 'B'), (9, 'C')]

但内置 zip 不会重复与更大尺寸的列表配对。 是否存在任何内置方式可以实现这一目标? 谢谢

这是我的代码

idx = 0
zip_list = []
for value in larger:
    zip_list.append((value,smaller[idx]))
    idx += 1
    if idx == len(smaller):
        idx = 0

【问题讨论】:

标签: python list python-3.x


【解决方案1】:

这个问题试图以错误的方式解决问题。

您在这里尝试的是获取两个给定列表的元素的所有可能排列。这可以使用itertools.product 轻松实现

>>> from itertools import product
>>> list(product(range(2), range(5)))
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]
>>> list(product(range(2), range(2)))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> list(product(range(2), range(2), range(3)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2)]

【讨论】:

    【解决方案2】:

    让我们使用np.tile 和zip:

    my_list = [1, 2, 3, 5, 5, 9]
    another_list = ['Yes', 'No']
    list(zip(my_list,np.tile(another_list, len(my_list)//len(another_list) + 1)) )
    

    输出:

    [(1, 'Yes'), (2, 'No'), (3, 'Yes'), (5, 'No'), (5, 'Yes'), (9, 'No')]
    

    【讨论】:

      【解决方案3】:

      我喜欢Henry Yik's answer,它执行起来有点快,但这里是不使用 itertools 的答案。

      my_list = [1, 2, 3, 5, 5, 9]
      another_list = ['Yes', 'No']
      
      new_list = []
      for i in range(len(my_list)):
          new_list.append([my_list[i], another_list[i % len(another_list)]])
      
      new_list
      
      [[1, 'Yes'], [2, 'No'], [3, 'Yes'], [5, 'No'], [5, 'Yes'], [9, 'No']]
      

      【讨论】:

        【解决方案4】:

        一个非常简单的方法是将短列表相乘以使其更长:

        my_list = [1, 2, 3, 5, 5, 9]
        another_list = ['Yes', 'No']
        
        zip(my_list, another_list*3))
        #[(1, 'Yes'), (2, 'No'), (3, 'Yes'), (5, 'No'), (5, 'Yes'), (9, 'No')]
        

        这里注意,乘数不需要仔细计算,因为zip 只得出最短列表的长度(并且乘数的目的是确保最短列表是my_list)。也就是说,如果使用100 而不是3,结果将是相同的。

        【讨论】:

          【解决方案5】:

          你可以使用itertools.cycle:

          from itertools import cycle
          
          my_list = [1, 2, 3, 5, 5, 9]
          another_list = ['Yes', 'No']
          
          cyc = cycle(another_list)
          
          print([[i, next(cyc)] for i in my_list])
          # [[1, 'Yes'], [2, 'No'], [3, 'Yes'], [5, 'No'], [5, 'Yes'], [9, 'No']]
          

          【讨论】:

            【解决方案6】:

            你可以使用itertools.cycle:

            创建一个迭代器,从可迭代对象中返回元素并保存每个元素的副本。当迭代耗尽时,从保存的副本中返回元素。无限重复。

            示例:

            A = [1,2,3,4,5,6,7,8,9]
            B = ["A","B","C"]
            
            from itertools import cycle
            zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)
            

            【讨论】:

              【解决方案7】:

              您可以在循环计数中使用取模 % 运算符

              my_list=[1, 2, 3, 5, 5, 9]
              another_list=['Yes','No']
              
              new_list = []
              for cur in range(len(my_list)):
                  new_list.append([my_list[cur], another_list[cur % 2]])
              # [[1, 'Yes'], [2, 'No'], [3, 'Yes'], [5, 'No'], [5, 'Yes'], [9, 'No']]
              

              2可以替换为len(another_list)

              【讨论】:

                【解决方案8】:

                试试这样:

                my_list=[  1,   2,   3, 5,  5,  9]
                another_list=['Yes','No']
                if type(len(my_list)/2) == float:
                  ml=int(len(my_list)/2)+1
                else:
                  ml=int(len(my_list)/2)
                
                print([[x,y] for x,y in zip(my_list,another_list*ml)])
                

                原生方式:

                • 尝试计算并舍入第一个列表长度的一半,如果是浮点数也加1
                • 在此之前使用zip() 进行迭代,然后将第二个 YesNo 列表与之前计算的数字相乘

                【讨论】:

                  【解决方案9】:

                  你知道第二个列表更短吗?

                  import itertools
                  list(zip(my_list, itertools.cycle(another_list)))
                  

                  这实际上会给你一个元组列表而不是一个列表列表。我希望没关系。

                  【讨论】:

                  • 最佳答案,因为不需要创建中间状态。如果 OP 真的需要列表,那么 [list(x) for x in zip(a, itertools.cycle(b))] 可以工作。
                  【解决方案10】:
                  d1=['one','two','three']
                  d2=[1,2,3,4,5]
                  

                  压缩

                  zip(d1,d2)
                  <zip object at 0x05E494B8>
                  

                  压缩包列表

                  list(zip(d1,d2))
                  

                  zip 列表字典

                  {'one': 1, 'two': 2, 'three': 3}
                  

                  注意:Python 3.7+

                  【讨论】:

                    【解决方案11】:

                    任意数量的可迭代对象的解决方案,并且您不知道哪个是最长的(也允许为任何空的可迭代对象设置默认值):

                    from itertools import cycle, zip_longest
                    
                    def zip_cycle(*iterables, empty_default=None):
                        cycles = [cycle(i) for i in iterables]
                        for _ in zip_longest(*iterables):
                            yield tuple(next(i, empty_default) for i in cycles)
                    
                    for i in zip_cycle(range(2), range(5), ['a', 'b', 'c'], []):
                        print(i)
                    

                    输出:

                    (0, 0, 'a', None)
                    (1, 1, 'b', None)
                    (0, 2, 'c', None)
                    (1, 3, 'a', None)
                    (0, 4, 'b', None)
                    

                    【讨论】:

                    • 这在大小相等的列表中不起作用
                    • @LuisSieira,它确实适用于相同的尺寸。如果您正在运行代码,那么您可能不小心在最后留下了空列表。您应该会发现此示例按预期工作 zip_cycle(range(3), range(3), ['a', 'b', 'c'])
                    【解决方案12】:

                    对于以任何顺序处理任何有限数量的潜在无限迭代的版本:

                    from itertools import cycle, tee, zip_longest
                    
                    def cyclical_zip(*iterables):
                        iterables_1, iterables_2 = zip(*map(tee, iterables))  # Allow proper iteration of iterators
                    
                        for _, x in zip(
                                zip_longest(*iterables_1),      # Limit             by the length of the longest iterable
                                zip(*map(cycle, iterables_2))): #       the cycling
                            yield x
                    
                    assert list(cyclical_zip([1, 2, 3], 'abcd', 'xy')) == [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'x'), (1, 'd', 'y')]  # An example and test case
                    

                    【讨论】:

                      【解决方案13】:

                      如今list comprehentions

                      [(i, B[i % 3 - 1]) for i in A]
                      

                      或者如果A的元素不是连续的并且不担心列表长度

                      [(j, B[i % len(B)]) for i, j in enumerate(A)] if len(A) >= len(B) else \
                      [(A[i % len(A)], j) for i, j in enumerate(B)]
                      

                      【讨论】:

                        【解决方案14】:

                        对称,无条件单行

                        [*zip(A*(len(B)//len(A) + 1), B*(len(A)//len(B) + 1))]
                        

                        严格回答'如何压缩两个不同大小的列表?'

                        需要一个相同大小列表的补丁才能通用:

                        [*(zip(A, B) if len(A) == len(B)
                                 else zip(A*(len(B)//len(A) + 1),
                                          B*(len(A)//len(B) + 1)))]
                        

                        【讨论】:

                          【解决方案15】:

                          可能有更好的方法,但您可以创建一个函数,将您的列表重复到您想要的任何长度。

                          def repeatlist(l,i):
                              '''give a list and a total length'''
                              while len(l) < i:
                                  l += l
                              while len(l) > i:
                                  l.pop()
                          

                          那就做吧

                          repeatlist(B,len(A))
                          zip_list = zip(A,B)
                          

                          【讨论】:

                            【解决方案16】:

                            试试这个。

                            A = [1,2,3,4,5,6,7,8,9]
                            B = ["A","B","C"]
                            Z = []
                            for i, a in enumerate(A):
                                Z.append((a, B[i % len(B)]))
                            

                            只需确保较大的列表位于 A 中。

                            【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2012-07-04
                              • 2015-11-04
                              • 1970-01-01
                              • 2016-08-28
                              • 2011-11-20
                              • 1970-01-01
                              相关资源
                              最近更新 更多