我如何编写一个 for 循环来遍历各种形式的可迭代对象?
How can I write a for-loop that iterates over various forms of iterables?
我正在编写一个 for 循环,它基本上迭代两个列表的乘积。在大多数情况下,定义了两个列表,因此迭代产品没有问题。但是,也有两个列表之一未定义的情况。此外,可能存在两个列表都未定义的情况。我能否更改以下代码片段中的函数 bar
,使其只有一个 single for-loop
来处理各种情况 without if statements
?
import itertools
def foo(a, b):
print(a, b)
def bar(lista, listb):
# How can I make this function more concise?
if lista and listb:
for a, b in itertools.product(lista, listb):
foo(a, b)
elif lista:
for a in lista:
foo(a, listb)
elif listb:
for b in listb:
foo(lista, b)
else:
foo(lista, listb)
print("Case #1. When both lists are defined.")
lista = [1, 2]
listb = [3, 4]
bar(lista, listb)
print("Case #2. When only lista defined.")
lista = [1, 2]
listb = None
bar(lista, listb)
print("Case #3. When only listb is defined.")
lista = None
listb = [3, 4]
bar(lista, listb)
print("Case #4. When neither of two list are defined.")
lista = None
listb = None
bar(lista, listb)
只需提前检查并用可接受的替代值替换 None
值:
import itertools
def bar(lista, listb):
if lista is None:
lista = [None]
if listb is None:
listb = [None]
for a, b in itertools.product(lista, listb):
foo(a, b)
虽然 IMO,但如果调用者必须处理将有效参数传递给 bar
会更好,并且 bar 假定输入始终是 non-None。
还有术语吹毛求疵,在所有情况下,lista
和 listb
都定义了 ,它们只是在某些情况下可以是 None
。这与未定义不同。由于您正在谈论函数的参数,因此它们将 始终被定义 。
请尝试以下功能。
def bar(lista, listb):
for a, b in itertools.product(*[lista or [None], listb or [None]]):
foo(a, b)
我正在编写一个 for 循环,它基本上迭代两个列表的乘积。在大多数情况下,定义了两个列表,因此迭代产品没有问题。但是,也有两个列表之一未定义的情况。此外,可能存在两个列表都未定义的情况。我能否更改以下代码片段中的函数 bar
,使其只有一个 single for-loop
来处理各种情况 without if statements
?
import itertools
def foo(a, b):
print(a, b)
def bar(lista, listb):
# How can I make this function more concise?
if lista and listb:
for a, b in itertools.product(lista, listb):
foo(a, b)
elif lista:
for a in lista:
foo(a, listb)
elif listb:
for b in listb:
foo(lista, b)
else:
foo(lista, listb)
print("Case #1. When both lists are defined.")
lista = [1, 2]
listb = [3, 4]
bar(lista, listb)
print("Case #2. When only lista defined.")
lista = [1, 2]
listb = None
bar(lista, listb)
print("Case #3. When only listb is defined.")
lista = None
listb = [3, 4]
bar(lista, listb)
print("Case #4. When neither of two list are defined.")
lista = None
listb = None
bar(lista, listb)
只需提前检查并用可接受的替代值替换 None
值:
import itertools
def bar(lista, listb):
if lista is None:
lista = [None]
if listb is None:
listb = [None]
for a, b in itertools.product(lista, listb):
foo(a, b)
虽然 IMO,但如果调用者必须处理将有效参数传递给 bar
会更好,并且 bar 假定输入始终是 non-None。
还有术语吹毛求疵,在所有情况下,lista
和 listb
都定义了 ,它们只是在某些情况下可以是 None
。这与未定义不同。由于您正在谈论函数的参数,因此它们将 始终被定义 。
请尝试以下功能。
def bar(lista, listb):
for a, b in itertools.product(*[lista or [None], listb or [None]]):
foo(a, b)