python - 动态嵌套循环 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]
有没有其他方法可以通过只指定变量N
而3
不是 x,y,z 来做到这一点?
我试过[]*3
但无法获得所需的输出。
解决方案
使用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]]
推荐阅读
- python - Python:在读取时区分 CSV 分隔符
- sql-server - SQL Server SQLPackage 漂移报告在 SQL Server 2017 上不起作用
- google-cloud-platform - 无法使用无服务器 VPC 访问设置 Google Cloud Memorystore redis 实例
- java - 如何使用 Java 8 Streams 迭代键值?
- bash - WSL - 当 Linux 二进制文件在 Bash 中不可用时如何回退到 exe
- android - 如何在 Android (Kotlin) 中获取日期
- excel - 多条件搜索并使用数组函数从表中返回多个值
- java - Java - 生成随机数
- c++ - 在 Arduino 下的 slack bot 上找不到频道,但不是 Bash
- javascript - JavaScript:如何异步自动递增计数器