gpt4 book ai didi

python - 在 Python 中为任意 n 嵌套 n 循环

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:58 25 4
gpt4 key购买 nike

那么,假设我有一个任意长的数字列表。我想获得该列表中每个数字乘以该列表中每个数字的列表。我会像这样嵌套 for 循环来做到这一点:

for x in numbers:
for y in numbers:
print(x*y)

现在,如果我想将该列表中的每个数字乘以该列表中的每个数字乘以该列表中的每个数字再次,我会这样做:

for x in numbers:
for y in numbers:
for z in numbers:
print(x*y*z)

我的问题是我正在为子图搜索一个图,我需要允许任意大的子图。为此,我必须用 n 个边从主图中的边构造每个子图 - 我必须允许 n 的任意值。怎么办?

最佳答案

itertools.product具有迭代乘积计算功能(我喜欢 reduce(mul, ...))。如果您需要 n 产品(在“产品”一词的两种意义上):

from functools import reduce
from operator import mul

for numset in itertools.product(numbers, repeat=n):
print(reduce(mul, numset))

上面很简单,但是当值集很大并且 n >= 3 时,它会不必要地重新计算部分乘积。可以使用递归函数来避免这种情况:

def compute_products(numbers, repeat):
if repeat == 1:
yield from numbers
return
numbers = tuple(numbers) # Only needed if you want to handle iterator/generator inputs
for prod in compute_products(numbers, repeat-1):
yield from (prod * x for x in numbers)

for prod in compute_products(numbers, n):
print(prod)

关于python - 在 Python 中为任意 n 嵌套 n 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32834106/

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