【问题标题】:Loop through multiple lists in specific intervals以特定间隔循环多个列表
【发布时间】:2018-09-06 06:39:19
【问题描述】:

我有两个列表。一个带有名称,一个带有与第一个列表中的名称对应的数字(对应的名称和数字在每个列表中的同一索引点)。我需要在一次只能处理 25 个不同名称和点的 url 中引用每个名称和数字。

pointNames = ['name1', 'name2', 'name3']
points = ['1', '2', '3']  #yes, the numbers are meant to be strings

我的实际列表中每个列表大约有 600 个值。我想要做的是同时循环遍历每个列表,但以 25 为增量。我可以使用以下方法对单个列表执行此操作:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

for group in chunker(pointNames, 25):
    print (group)

这会从列表中打印多组 25 个值,直到它遍历整个列表。我想这样做,但有两个列表。我可以使用 for(point, name) in zip(points, pointNames): 完全打印每个列表,但我需要 25 个一组。

我也尝试过将这两个列表组合成一个字典:

dictionary = dict(zip(points, pointNames))

for group in chunker(dictionary, 25):
    print (group)

但我收到以下错误:

TypeError: unhashable type: 'slice'

【问题讨论】:

    标签: python python-3.x list loops dictionary


    【解决方案1】:

    对你的第一个函数做这个相对最小的改变怎么样:

    def chunker(seq1, seq2, size):
        seq = list(zip(seq1, seq2))
        return (seq[pos:pos + size] for pos in range(0, len(seq), size))
    

    调用如下:

    for group in chunker(pointNames, points, 25):
        print(group)
    

    【讨论】:

      【解决方案2】:

      生成器会更高效:

      import itertools
      
      def chunker(size, *seq):
          seq = zip(*seq)
          while True:
              val = list(itertools.islice(seq, size))
              if not val:
                  break
              yield val
      
      
      for group in chunker(2, pointNames, points):
          print(group)
      
      gen_groups = chunker(2, pointNames, points, pointNames, points)
      group = next(gen_groups)
      print(group)
      

      使用*seq 允许您提供任意数量的列表作为参数。

      【讨论】:

      • 这很好用。允许我在每个循环中使用group[n][n] 从给定的 25 个集合中引用一个单独的名称或号码。我所做的一项更正是在您的 gen_groups 变量上 - 删除了重复的 pointNames, points
      • @Aaron 这只是为了表明您可以传递任意数量的列表。
      • 嗯,我明白了。谢谢
      【解决方案3】:

      Itertools 可以将迭代器(或生成器)分割成块,以及一个小的帮助函数以继续执行直到完成:

      import itertools
      
      # helper function, https://stackoverflow.com/a/24527424
      def chunks(iterable, size=10):
          iterator = iter(iterable)
          for first in iterator:
              yield itertools.chain([first], itertools.islice(iterator, size - 1))
      
      
      # 600 points and pointNames
      points = (str(i) for i in range(600))
      pointNames = ('name ' + str(i) for i in range(600))
      
      # work with the chunks
      for chunk in chunks(zip(pointNames, points), 25):
          print('-' * 40)
          print(list(chunk))
      

      【讨论】:

        猜你喜欢
        • 2016-10-02
        • 2021-02-06
        • 2017-11-12
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-05
        相关资源
        最近更新 更多