[英]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.