我在 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")
关于python - 简化 Python 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71461635/