Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.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 在一个列表中查找一对数字,其总和为10_Python - Fatal编程技术网

Python 在一个列表中查找一对数字,其总和为10

Python 在一个列表中查找一对数字,其总和为10,python,Python,给出一个数字列表,我想找出所有加起来等于10的数字对 如何在Python中编写函数来实现这一点?只需将10的差异存储在一个集合中: def find(arr, total): d = set() for e in arr: if e in d: print total-e, e break d.add(total-e) s = [1,5,3,10,11,7,2] find(s, 10) 一个很好的

给出一个数字列表,我想找出所有加起来等于10的数字对


如何在Python中编写函数来实现这一点?

只需将10的差异存储在一个集合中:

def find(arr, total):
    d = set()
    for e in arr:
        if e in d:
            print total-e, e
            break
        d.add(total-e)

s = [1,5,3,10,11,7,2]
find(s, 10)

一个很好的小例子大约需要三分钟。我印象深刻。:)您应该使用
set
而不是
dict
来测试成员资格。很高兴这是
O(n)
。存储补码并查看它们何时被找到是一种很好的方法。您有一个错误:您在s中为e编写了
,但您的意思是在arr中为e编写
,很难说您需要什么。你能举一些输入和输出的例子吗?
l = [1, 3, 4, 5, 6, 7, 8, 9]
[(x,y) for x in l for y in l if x+y==10]