在Python中,我尝试在N
列表列表中添加元素的所有不同组合,其中N
是变量。具体来说,我正在使用包含列表[1, 2, 3, 4, 5, 6]
的N个副本的列表。
所以让我们假设N = 3
。我想循环浏览第一个列表,添加:
6 + 6 + 6
5 + 6 + 6
...
1 + 6 + 6`
然后增加第二个人并开始添加:
6 + 5 + 6
5 + 5 + 6
...
1 + 1 + 1 # ultimately to
当然我增加了第三个人。这个具体的例子可以用3个嵌套的for循环来完成,但当然,我需要改变循环的数量。我在网络和这个论坛上搜索答案,并且不能完全掌握我应该做的事情。人们一直在说使用递归函数,但在我查看之前我从未听说过。所以很难掌握。
答案 0 :(得分:0)
为了实现这一目标,您可以使用itertools.product
作为:
from itertools import product
my_list = [1, 2, 3, 4, 5, 6]
N=3
# value of `N` v
for s in product(my_list[::-1], repeat=N):
print '{} : {}'.format(s[::-1], sum(s))
# No need to reverse here ^
# since sum(s[::-1]) and sum(s) will give same result
将打印:
# (combination) : sum
(6, 6, 6) : 18
(5, 6, 6) : 17
(4, 6, 6) : 16
(3, 6, 6) : 15
(2, 6, 6) : 14
(1, 6, 6) : 13
...
(6, 1, 1) : 8
(5, 1, 1) : 7
(4, 1, 1) : 6
(3, 1, 1) : 5
(2, 1, 1) : 4
(1, 1, 1) : 3
如果您只想将值存储在list
中,则可以使用 list comprehension 表达式:
>>> [sum(s) for s in product(my_list[::-1], repeat=3)]
[18, 17, 16, 15, 14, 13, 17, 16, 15, 14, 13, 12, 16, 15, 14, 13, 12, 11, 15, 14, 13, 12, 11, 10, 14, 13, 12, 11, 10, 9, 13, 12, 11, 10, 9, 8, 17, 16, 15, 14, 13, 12, 16, 15, 14, 13, 12, 11, 15, 14, 13, 12, 11, 10, 14, 13, 12, 11, 10, 9, 13, 12, 11, 10, 9, 8, 12, 11, 10, 9, 8, 7, 16, 15, 14, 13, 12, 11, 15, 14, 13, 12, 11, 10, 14, 13, 12, 11, 10, 9, 13, 12, 11, 10, 9, 8, 12, 11, 10, 9, 8, 7, 11, 10, 9, 8, 7, 6, 15, 14, 13, 12, 11, 10, 14, 13, 12, 11, 10, 9, 13, 12, 11, 10, 9, 8, 12, 11, 10, 9, 8, 7, 11, 10, 9, 8, 7, 6, 10, 9, 8, 7, 6, 5, 14, 13, 12, 11, 10, 9, 13, 12, 11, 10, 9, 8, 12, 11, 10, 9, 8, 7, 11, 10, 9, 8, 7, 6, 10, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 4, 13, 12, 11, 10, 9, 8, 12, 11, 10, 9, 8, 7, 11, 10, 9, 8, 7, 6, 10, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 4, 8, 7, 6, 5, 4, 3]
答案 1 :(得分:0)
您可以使用 itertools.combinations_with_replacement
来解决此问题。
In []: from itertools import combinations_with_replacement
In []: for combination in combinations_with_replacement(range(1, 7), 3):
print("Combination: ", combination, " Sum: ", sum(combination))
....:
Combination: (1, 1, 1) Sum: 3
Combination: (1, 1, 2) Sum: 4
Combination: (1, 1, 3) Sum: 5
Combination: (1, 1, 4) Sum: 6
Combination: (1, 1, 5) Sum: 7
Combination: (1, 1, 6) Sum: 8
.
.
.
Combination: (4, 5, 6) Sum: 15
Combination: (4, 6, 6) Sum: 16
Combination: (5, 5, 5) Sum: 15
Combination: (5, 5, 6) Sum: 16
Combination: (5, 6, 6) Sum: 17
Combination: (6, 6, 6) Sum: 18
如果您想将总和存储在list
中,可以使用列表理解:
list_of_sums = [sum(combination) for combination in combinations_with_replacement(range(1, 7), 3)]