简化 Python 中的 for 循环
Simplifying for loop in Python
我在 Python 中有这样的代码片段:
#list_1 have a previous value that we dont know
n = 40 #This value can change
list_2 = [0, 0, 0, 0]
#We are trying all the values possibles for 4 positions and 40 different numbers
for a in range(n):
for b in range(n):
for c in range(n):
for d in range(n):
list_2[0] = a
list_2[1] = b
list_2[2] = c
list_2[3] = d
if list_1 == list_2:
print("Ok")
我想将嵌套的 for
循环更改为更简单的东西;我能做什么?
使用itertools.product()
和repeat
参数来减少嵌套量:
from itertools import product
for a, b, c, d in product(range(n), repeat=4):
list_2 = [a, b, c, d] # Can condense the assignments into one line as well.
if list_1 == list_2:
print("Ok")
您可以通过执行以下操作将此概括为大于 4 的列表:
from itertools import product
x = # length of lists to find matches for
for item in product(range(n), repeat=x):
list_2 = list(item)
if list_1 == list_2:
print("Ok")
一些方法,一些使用 itertools.product
...
for [*list_2] in product(range(n), repeat=4):
if list_1 == list_2:
print("Ok")
list_2 = []
for list_2[:] in product(range(n), repeat=4):
if list_1 == list_2:
print("Ok")
if tuple(list_1) in product(range(n), repeat=4):
print("Ok")
if list_1 in map(list, product(range(n), repeat=4)):
print("Ok")
if len(list_1) == 4 and all(x in range(n) for x in list_1):
print("Ok")
if len(list_1) == 4 and set(list_1) <= set(range(n)):
print("Ok")
我在 Python 中有这样的代码片段:
#list_1 have a previous value that we dont know
n = 40 #This value can change
list_2 = [0, 0, 0, 0]
#We are trying all the values possibles for 4 positions and 40 different numbers
for a in range(n):
for b in range(n):
for c in range(n):
for d in range(n):
list_2[0] = a
list_2[1] = b
list_2[2] = c
list_2[3] = d
if list_1 == list_2:
print("Ok")
我想将嵌套的 for
循环更改为更简单的东西;我能做什么?
使用itertools.product()
和repeat
参数来减少嵌套量:
from itertools import product
for a, b, c, d in product(range(n), repeat=4):
list_2 = [a, b, c, d] # Can condense the assignments into one line as well.
if list_1 == list_2:
print("Ok")
您可以通过执行以下操作将此概括为大于 4 的列表:
from itertools import product
x = # length of lists to find matches for
for item in product(range(n), repeat=x):
list_2 = list(item)
if list_1 == list_2:
print("Ok")
一些方法,一些使用 itertools.product
...
for [*list_2] in product(range(n), repeat=4):
if list_1 == list_2:
print("Ok")
list_2 = []
for list_2[:] in product(range(n), repeat=4):
if list_1 == list_2:
print("Ok")
if tuple(list_1) in product(range(n), repeat=4):
print("Ok")
if list_1 in map(list, product(range(n), repeat=4)):
print("Ok")
if len(list_1) == 4 and all(x in range(n) for x in list_1):
print("Ok")
if len(list_1) == 4 and set(list_1) <= set(range(n)):
print("Ok")