Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中随机列表的求和_Python_List_Random_Sum_Zero - Fatal编程技术网

python中随机列表的求和

python中随机列表的求和,python,list,random,sum,zero,Python,List,Random,Sum,Zero,我已经创建了一个60个数字的随机列表,我不知道列表中包含的数字。我被要求从列表中找出三个和为零的数字的任意组合。我能做什么? 这是我的密码: import random import itertools result = [] for x in range (-30, 30): num = random.randint(-30, 30) while num in result: num = random.randint(-30, 30) result.appen

我已经创建了一个60个数字的随机列表,我不知道列表中包含的数字。我被要求从列表中找出三个和为零的数字的任意组合。我能做什么? 这是我的密码:

import random
import itertools
result = []

for x in range (-30, 30):
   num = random.randint(-30, 30)
   while num in result:
     num = random.randint(-30, 30)
     result.append(num)
        result = [seq for i in range(len(result), 0, -1) for seq in itertools.combinations(result, i) if sum(seq) == 0]
print result

为了演示的目的,我将为
result
定义一个特定的示例值,我们可以使用该值进行测试,看看会发生什么

result = [1, 2, -2, -3, 4]
您可以使用
itertools.combinations
列出三个数字的所有组合

import itertools

>>> list(itertools.combinations(result, 3))
[(1, 2, -2),
 (1, 2, -3),
 (1, 2, 4),
 (1, -2, -3),
 (1, -2, 4),
 (1, -3, 4),
 (2, -2, -3),
 (2, -2, 4),
 (2, -3, 4),
 (-2, -3, 4)]
您可以使用
filter
lambda c:sum(c)==0
作为谓词来选择和为零的组合

>> list(filter(lambda c: sum(c) == 0, itertools.combinations(result, 3)))
[(1, 2, -3)]

itertools
中有一个函数
combines
,可用于生成组合

import random
import itertools
# Generate a random list of 30 numbers
mylist = random.sample(range(-50,50), 30)

combins = itertools.combinations(mylist, 3)
interested = list(filter(lambda combin: sum(combin) == 0, combins))
print(interested)
请注意,来自
filter()
itertools.compositions()
的结果是iterables,需要
list()
将iterable转换为列表

lambda表达式
lambda combi:sum(combi)=0
用于从
combis

itertools.compositions()

过滤器()

到目前为止,您尝试了什么?请包括您已经尝试过的代码。(列表是如何制作的,您已经尝试让他们添加了什么。)我的总和代码不在这里,因为它不起作用!不起作用的过帐代码有点像堆栈溢出。我们可以看看它,告诉你你做错了什么。请注意让代码显示为代码。我不知道列表中的数字!我能做什么?你什么意思?为什么您需要知道它们?您使用数字1、2、-2等。我不知道列表中的数字。我将
结果定义为一组特定的数字,以便向您展示发生的情况。但是代码适用于任何一组数字,不仅仅是示例。我刚刚在上面添加了我的代码,如何从我创建的列表中获得任何组合,总和为零?:)列表是随机生成的,因此如果幸运的话,感兴趣的列表可能是空的。然后重新运行脚本。