【发布时间】:2020-05-31 01:36:09
【问题描述】:
我正在尝试创建一个包含列表所有组合元素的函数。细节是这样的。
这是当列表元素为 [1,2,3] 且 n=4 时。 例如,
elements=[1,2,3]
all_data=[]
for x_1 in elements:
tmp=[]
tmp.append(x_1)
all_data.append(tmp)
for x_2 in elements:
tmp=[]
tmp.append(x_1)
tmp.append(x_2)
all_data.append(tmp)
for x_3 in elements:
tmp=[]
tmp.append(x_1)
tmp.append(x_2)
tmp.append(x_3)
all_data.append(tmp)
for x_4 in elements:
tmp=[]
tmp.append(x_1)
tmp.append(x_2)
tmp.append(x_3)
tmp.append(x_4)
all_data.append(tmp)
all_data
输出是→
[[1],
[1, 1],
[1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 2],
[1, 1, 1, 3],
[1, 1, 2],
[1, 1, 2, 1],
[1, 1, 2, 2],
[1, 1, 2, 3],
[1, 1, 3],
[1, 1, 3, 1],
[1, 1, 3, 2],
[1, 1, 3, 3],
[1, 2],
[1, 2, 1],
[1, 2, 1, 1],
[1, 2, 1, 2],
[1, 2, 1, 3],
[1, 2, 2],
[1, 2, 2, 1],
[1, 2, 2, 2],
[1, 2, 2, 3],
[1, 2, 3],
[1, 2, 3, 1],
[1, 2, 3, 2],
[1, 2, 3, 3],
[1, 3],
[1, 3, 1],
[1, 3, 1, 1],
[1, 3, 1, 2],
[1, 3, 1, 3],
[1, 3, 2],
[1, 3, 2, 1],
[1, 3, 2, 2],
[1, 3, 2, 3],
[1, 3, 3],
[1, 3, 3, 1],
[1, 3, 3, 2],
[1, 3, 3, 3],
[2],
[2, 1],
.....
[3, 2, 3],
[3, 2, 3, 1],
[3, 2, 3, 2],
[3, 2, 3, 3],
[3, 3],
[3, 3, 1],
[3, 3, 1, 1],
[3, 3, 1, 2],
[3, 3, 1, 3],
[3, 3, 2],
[3, 3, 2, 1],
[3, 3, 2, 2],
[3, 3, 2, 3],
[3, 3, 3],
[3, 3, 3, 1],
[3, 3, 3, 2],
[3, 3, 3, 3]]
但我想要实现的是使用(可能)循环语句将这个功能做 n 次。 所以,我想做的函数输出应该是这样的,
[[1],
[1,1],
......
[1,1,1,1,......,1], #(1 of n times)
[1,1,1,1,......,2],
......
[6],
[6,6],
......
[6,6,6,6,......,6]] #(n times)
虽然我花了几乎整整一周的时间来解决这个问题,但还没有找到任何解决方案。 谁能给我一些提示或碰巧知道任何想法? 任何线索都非常受欢迎。
谢谢。
【问题讨论】:
-
这有点像 powerset,所以也许你可以调整 powerset 配方。见How to get all subsets of a set? (powerset)
标签: python list function numpy