简体   繁体   English

在列表列表中查找所有无的最 Pythonic 方法是什么?

[英]What is the most Pythonic way to find all Nones in a list of lists?

Is there a better Pythonic way to find all Nones in a list of lists than this code?有没有比这段代码更好的 Pythonic 方法来查找列表列表中的所有无?

    def find_nones_locations(lst):
         none_locations = []
         for i in range(len(lst)):
              for j in range(len(lst)):
                   if lst[i][j] is None:
                        none_locations.append((i,j))
         return none_locations

You can use a list comprehension to do it in one shot, but I'm not sure it's necessarily better than a legible loop:您可以使用列表推导一次性完成,但我不确定它是否一定比清晰的循环更好:

none_locations = [(i, j) for i, row in enumerate(lst) for j, elem in enumerate(row) if elem is None]

Nested loops in comprehensions follow the same order they do in plain code.理解中的嵌套循环遵循它们在纯代码中的顺序。 There's no good reason not to use a plain loop:没有充分的理由不使用普通循环:

none_locations = []
for i, row in enumerate(lst):
    for j, elem in enumerate(row):
        if elem is None:
            none_locations.append((i, j))

The only potential improvement over your code is the use of the enumerate generator.对代码的唯一潜在改进是使用enumerate生成器。 Any time you need both the index and the value of an iterable, that's generally the pythonic way to get it.任何时候你需要一个可迭代对象的索引和值,这通常是获取它的 Python 方式。

You can use enumerate to clean up the code a bit:您可以使用enumerate来稍微清理一下代码:

def find_nones_locations(lst):
     none_locations = []
     for i, sublst in enumerate(lst):
          for j, item in enumerate(sublist):
               if item is None:
                    none_locations.append((i,j))
     return none_locations

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在列表中找到与其他元素不同的元素的最pythonic方法是什么? - what is most pythonic way to find a element in a list that is different with other elements? 什么是确保列表中所有元素不同的最pythonic方法? - What's the most pythonic way to ensure that all elements of a list are different? 查找列表列表的最长公共前缀的 Pythonic 方法是什么? - What is the Pythonic way to find the longest common prefix of a list of lists? 将列表的字典转换为字典中所有元素的所有组合的字典列表的最有效方法? - Most pythonic way to convert a dict of lists into a list of dicts of all combs of the elements in the lists from the dict? 遍历一长串字符串并从原始列表构建新列表的最pythonic 方法是什么? - What is the most pythonic way to iterate through a long list of strings and structure new lists from that original list? 列表边界-最Python的方式是什么? - List boundaries - what is the most Pythonic way? 以最pythonic的方式将列表列表复制到另一个列表的一部分中 - Copying a list of lists into part of another one in the most pythonic way 映射字典列表的最Pythonic方法是什么? - What is the most Pythonic way to map-process lists of dictionaries? 大多数“pythonic”方式来检查列表的子列表的排序? - Most “pythonic” way to check ordering of sub lists of a list? 列表的另一个合并列表,但大多数pythonic方式 - Yet another merging list of lists, but most pythonic way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM