python - 简化 Python 中的 for 循环

标签 python for-loop nested-loops

我在 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/

相关文章:

python - 分支列表排序

python - 获取 Flask 请求数据

for-loop - 对于范围与静态 channel 长度 golang

python - 嵌套字典的迭代器类

python - 无法重复迭代 "csv.reader"- 第二次迭代的结果为空

python - 使用 Python 安装 Gaphor 时 PYPATH 无注册表项错误

python - 为什么最后一个命令变量 "_"没有出现在 dir() 中?

Java for-each 循环抛出 NullPointErexception

javascript - 如果在迭代 javascript 循环时使用 "in"和 "="运算符有什么区别?

python - 删除 python 中的嵌套循环