gpt4 book ai didi

python - 与 map 函数相比,Python 中的嵌套 for 循环

转载 作者:太空狗 更新时间:2023-10-30 01:55:42 28 4
gpt4 key购买 nike

我在 python 中工作,目前有以下代码:

list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))

其中 run(a,b,c) 返回一个整数(例如,它可以将三个数字相乘)。有没有更快的方法来遍历这些数字或使用映射函数?

谢谢:)

最佳答案

看看 itertools-module特别是 product method

示例用法:

for i in itertools.product(range(0,100), repeat=3):
#do stuff with i
list.append(run(i[0],i[1],i[2]))

请注意,函数调用可以缩短为:

list.append(run(*i))

在上面的例子中。见docs.python.org解包参数列表的解释。

例如,product(range(0,2), repeat=3)) 的输出如下所示:

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

关于python - 与 map 函数相比,Python 中的嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330300/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com