【问题标题】:Find length of sublists for iteration查找子列表的长度以进行迭代
【发布时间】:2014-11-25 22:50:36
【问题描述】:
intlist = [[1,2,3],[6,5,4],[5,7,9],[6,2,6]]

intlist 可以是基于用户输入的任何内容,但每个子集中的元素数量应相同。我正在尝试从每个子列表中提取最大的 even 整数到一个新列表中。在这种情况下,[2,6,0,6] 将被返回。

我想知道如何找到给定子列表的长度(依次是每个子列表的长度),以便我可以遍历那么多元素。

for r in range(len(intlist)):
    for c in range(?): #Range here should be length of sublist
        if intlist[r][c] % 2 == 0:
            #if it is even, choose max even value.

【问题讨论】:

    标签: python list loops iteration


    【解决方案1】:

    您在寻找子列表吗?那只是intlist[r]。它不是超级 Pythonic,但是:

    for r in range(len(intlist)):
        for c in range(len(intlist[r])): #Range here should be length of sublist
            if intlist[r][c] % 2 == 0:
                #if it is even, choose max even value.
    

    您可以逐步清理它。例如,从查找子列表开始,而不是过多地依赖索引。

    for sublist in intlist:
        for c in range(len(sublist)): #Range here should be length of sublist
            if sublist[c] % 2 == 0:
                #if it is even, choose max even value.
    

    然后你可以去掉子索引,如果你需要的只是值:

    for sublist in intlist:
        for value in sublist:
            if value % 2 == 0:
                #if it is even, choose max even value.
    

    【讨论】:

      【解决方案2】:

      在 Python 中很少使用像 range(len(intlist)) 这样的东西是最好的方法,所以如果你发现自己写了这样的东西,那就表明有更好的方法来做。

      您可以使用传统的嵌套 for 循环来做到这一点。例如,

      #! /usr/bin/env python
      
      intlist = [[1,2,3],[6,5,4],[5,7,9],[6,2,6]]
      
      maxlist = []
      for sublist in intlist:
          evens = []
          for i in sublist:
              if i % 2 == 0:
                  evens.append(i)
          if evens:
              maxlist.append(max(evens))
          else:
              maxlist.append(0)
      print maxlist
      

      但是,使用列表推导式更简洁、更高效。

      print [max([i for i in sublist if i % 2 == 0] or [0]) for sublist in intlist]
      

      或者分两个阶段,

      evenlist = [[i for i in sublist if i % 2 == 0] for sublist in intlist]
      print [max(sublist or [0]) for sublist in evenlist]
      

      or [0] 在子列表不包含偶数时提供默认列表,否则 max 引发 ValueError: max() arg is an empty sequence

      就个人而言,如果子列表不包含任何偶数,我会倾向于返回 None。这样,您可以区分 0 实际上是存在的最高偶数的情况和列表中没有偶数的情况。但我想在这种情况下什么是最好的取决于您正在处理的数据以及您最终将使用它做什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-06
        • 2018-02-02
        • 2020-12-09
        • 1970-01-01
        • 2017-07-09
        • 2022-11-11
        • 2022-01-23
        • 2017-10-15
        相关资源
        最近更新 更多