Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何压缩两个不同大小的列表?_Python_List_Python 3.x - Fatal编程技术网

Python 如何压缩两个不同大小的列表?

Python 如何压缩两个不同大小的列表?,python,list,python-3.x,Python,List,Python 3.x,我想压缩两个不同长度的列表 比如说 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 lar

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

比如说

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
您可以使用:

制作一个迭代器,返回iterable中的元素并保存每个元素的副本。当iterable用完时,从保存的副本返回元素。无限期地重复

示例:

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)
试试这个

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

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

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

对称,无条件一行

[*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)))]
而现在

或者如果
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)]

对于以任意顺序处理任意数量的潜在无限多个ITerable的版本:

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

对于任意数量的iterables,您不知道哪一个最长(也允许任何空iterables的默认值):

产出:

(0, 0, 'a', None)
(1, 1, 'b', None)
(0, 2, 'c', None)
(1, 3, 'a', None)
(0, 4, 'b', None)
拉链 zip列表字典 注意:Python 3.7+

您可以使用:

试着这样做:

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)])
本地方式:

  • 尝试计算并四舍五入第一个列表长度的一半,如果它是float,则也添加1
  • 在此之前使用
    zip()
    进行迭代,将第二个YesNo列表与之前计算的数字相乘
    • 让我们使用和
      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')]
      

      你知道第二张名单更短吗

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

      这实际上会给您一个元组列表,而不是列表列表。我希望没问题。

      一个非常简单的方法是将短列表相乘,这样它就更长了:

      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
      ,结果将是相同的。您可以在一个递增的循环中使用模
      %
      运算符

      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(另一个列表)

      我喜欢,而且执行起来有点快,但是这里有一个不使用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']]
      

      请检查此答案:最佳答案,因为不需要创建中间状态。如果OP真的需要列表,那么
      [zip中x的列表(x)(a,itertools.cycle(b))]
      可以工作。
      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']]
      
      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)])
      
      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')]
      
      import itertools
      list(zip(my_list, itertools.cycle(another_list)))
      
      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')]
      
      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']]
      
      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']]