【发布时间】:2017-08-17 14:13:08
【问题描述】:
我正在尝试打印列表的所有可能组合,但前提是这些组合加起来是一个数字。
lst = [0, 1, 2] #The goal is print all combinations that sum up to 3
import itertools
def fun(lst, total):
sum = 0
for element in lst:
sum += element
all_possible_combinations = set(itertools.product(lst, repeat=2)) # This prints all possible combinations of the elements in the list with length of 2
for items in all_possible_combinations:
a = 0
for i in items:
a += i
if a == total:
x = items
print(x)
print('These are all combinations:', all_possible_combinations)
fun([0, 1, 2], 2)
此程序打印总和为 3 的列表,但它多次打印这些列表。
>>>>>>>>
(2, 0)
(1, 1)
(0, 2) #I was expecting the programme to stop here.
(2, 0)
(1, 1)
(0, 2)
(2, 0)
(1, 1)
(0, 2)
These are all combinations: {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)}
>>>>>>>>
我认为这是因为 for element in lst: 循环,所以我尝试在此循环之外打印
import itertools
def fun(lst, total):
sum = 0
for element in lst:
sum += element
all_possible_combinations = set(itertools.product(lst, repeat=2)) # This prints all possible combinations of the elements in the list with length of 2
for items in all_possible_combinations:
a = 0
for i in items:
a += i
if a == total:
x = items
print(x)
print('These are all combinations:', all_possible_combinations)
fun([0, 1, 2], 2)
这个程序只返回一个列表
>>>>>>>>>
(0, 2)
>>>>>>>>>
我该如何纠正这个问题?我期待最终结果是
>>>>>>>>>
(2, 0)
(1, 1)
(0, 2)
>>>>>>>>>
【问题讨论】:
-
您的要求似乎搞砸了。你说你想要总和到列表总数的组合......但是你传递了一个总数。它是哪个?问题部分在于
for...您为列表中的每个项目执行整个算法。尝试使用sum(lst)并完全跳过那些添加 for 循环。你的代码会更清晰。 -
是的,我也有同样的疑问,所以我在答案中添加了一个
sum_list变量(根据您的实际要求进行更改)。你也只需要那些长度= 2的列表吗?请进行适当的更改。 -
总的来说,最好把它作为一个论据,因为它可能会不时改变。列表的长度可以超过 2,但这是一个非常简化的版本,它帮助我思考并实际解决了真正的问题。非常感谢
-
我已编辑问题以反映这一点
标签: python list for-loop while-loop itertools