我想编写一个递归代码,找到所有可以从列表中重复选择的 k
元素的选项。该代码将返回包含所有选项的列表的列表。
我的代码:
def repetitions(elements,k):
if elements==[]:
return []
if k==0:
return [[]]
else:
result=[]
result = repetitions(elements,k-1)
for e in result:
e.append(elements[0])
result.extend(repetitions(elements[1:],k))
return result
我的问题是代码不保留原始列表的顺序。
例如:
repetitions([1,2],3)
[[1, 1, 1], [2, 1, 1], [2, 2, 1], [2, 2, 2]]
而不是:
[[1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 2, 2]]
如何修复我的代码?
感谢任何帮助。
最佳答案
要获得正确的顺序,只需从开头插入而不是结尾:因此替换
e.append(elements[0])
作者:
e.insert(0,elements[0])
无论如何,为什么要重新发明轮子呢?只需使用 itertools.combinations_with_replacement
import itertools
def repetitions(r,n):
return list(itertools.combinations_with_replacement(r,n))
print(repetitions([1,2],3))
结果:
[(1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]
(或 [list(x) for x in itertools.combinations_with_replacement(r,n)]
如果您确实需要列表列表而不是元组列表)
小挑剔:
-
if elements==[]
=>if elements
- 无需设置
result = []
因为它是在下一行分配的
关于python - 查找列表中给定长度元素中具有重复项的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274501/