首页 > 解决方案 > 动态嵌套循环 Python

问题描述

这是我需要的数组:

N = 6
A = [[x,y,z] for x in range(N+1) for y in range(N+1) for z in range(N+1) if x+y+z== N]

有没有其他方法可以通过只指定变量N3不是 x,y,z 来做到这一点?
我试过[]*3但无法获得所需的输出。

标签: pythonlist-comprehension

解决方案


使用itertools.combinations_with_replacement

from itertools import combinations_with_replacement
n = 6
k = 3

# If you want a list of tuples:
lst = [item for item in list(combinations_with_replacement(range(n), k)) if sum(item) == n]
print(lst)
# [(0, 1, 5), (0, 2, 4), (0, 3, 3), (1, 1, 4), (1, 2, 3), (2, 2, 2)]

# If you want a list of lists:
lst = [list(item) for item in list(combinations_with_replacement(range(n), k)) if sum(item) == n]
print(lst)
# [[0, 1, 5], [0, 2, 4], [0, 3, 3], [1, 1, 4], [1, 2, 3], [2, 2, 2]]

推荐阅读