Python 在嵌套循环中传递“None”时避免“'NoneType'对象不可iterable”错误
我尝试将三个列表传递到一个函数中,该函数将迭代列表中的所有值,并将它们激发到另一个函数中:Python 在嵌套循环中传递“None”时避免“'NoneType'对象不可iterable”错误,python,Python,我尝试将三个列表传递到一个函数中,该函数将迭代列表中的所有值,并将它们激发到另一个函数中: def main(): l1 = [0,1] l2 = [1,5,10,20] l3 = [15] my_func(l1,l2,l3) def my_func(l1, l2, l3): nested = ((x,y,x) for x in l1 for y in l2 for z in l3) for x,y,z in nested: a
def main():
l1 = [0,1]
l2 = [1,5,10,20]
l3 = [15]
my_func(l1,l2,l3)
def my_func(l1, l2, l3):
nested = ((x,y,x) for x in l1 for y in l2 for z in l3)
for x,y,z in nested:
another_func(x,y,z)
def another_func(x,y,z):
...
但是,有时我需要将None值作为列表之一传入:
l3 = None
这会导致错误:TypeError:“NoneType”对象不可iterable,因为它在尝试迭代时不喜欢None值
我想知道如果列表的值为None,是否有任何方法可以将其从迭代中排除?因此我想我要寻找的是以下内容:
list(itertools.product(*filter(None, (a,b,c))))
这将循环所有可能的迭代并过滤列表中的“无”。这里我将遍历所有列表,将“无”替换为“无”,这是一个元组,因此是可编辑的
from itertools import repeat, product
def my_func(*lists):
for group in product(*(l if l is not None else (None,) for l in lists)):
another_func(*group)
你的意思是嵌套=x,y,z…?是l3是无的,你期望z值是什么?我期望它们也是无的,对吗?