Python 返回列表中总和为给定目标的数字

Python 返回列表中总和为给定目标的数字,python,performance,list,Python,Performance,List,o/p: 第一个数字是1,第二个数字是5 我遇到了这个问题,我使用以下代码解决了它: input = x[1,2,4,6,3,9] target = 6 def搜索(a,b): 对于b中的d: 如果a==d: m=真 打破 其他: m=假 返回m x=[1,4,5,7,9,6,2] target=int(原始输入(“输入数字”)) 对于x中的i: 如果我我的想法如下: def search(a,b): for d in b: if a==d: m

o/p: 第一个数字是1,第二个数字是5

我遇到了这个问题,我使用以下代码解决了它:

input = x[1,2,4,6,3,9]
target = 6
def搜索(a,b):
对于b中的d:
如果a==d:
m=真
打破
其他:
m=假
返回m
x=[1,4,5,7,9,6,2]
target=int(原始输入(“输入数字”))
对于x中的i:
如果我我的想法如下:

def search(a,b):
    for d in b:
        if a==d:
            m=True
            break
        else:
            m=False
    return m

x=[1,4,5,7,9,6,2]
target=int(raw_input("Enter the number:"))
for i in x:
    if i<target:
        pair=int(target)-int(i)
        in2=search(pair,x)
        if in2==True:
            print "the first number= %d the second number %d"%(i,pair)
            break

基本上,我在循环中迭代两次,搜索第一个索引+其他一些索引等于目标编号的情况,然后是第二个索引,依此类推。我希望我能帮上忙。您可以在打印后添加一个
quit()
,以在第一次找到匹配项后退出。祝你好运

与Damian的答案相同,但使用itertools

x = [1, 4, 5, 7, 9, 6, 2]
target = int(raw_input("Enter the number:"))
for i in xrange(len(x)):
    for ii in xrange(len(x)):
        if (x[i] + x[ii]) == target:
            print "the first number= %d the second number %d" % (x[i], x[ii])

如果
x
中的元素严格为正,则在创建组合之前,应删除大于或等于目标的所有元素。

您可以获得与所需目标相加的数字对列表:

import itertools
x=[1, 4, 5, 7, 9, 6, 2]
target=6
for l in itertools.combinations(x,2):
    if l[0]+l[1]==target:
         print("the first number= %d the second number %d" % l)
一般的做法是:

>>> [(x,y) for x in [1,2,3] for y in [1,2,3] if x+y == 3]
[(1, 2), (2, 1)]
以防你只需要数字而不需要配对

>>> [(x,y) for x in lst for y in lst if x+y == target]

这可能不是最有效的方法,但这是一种类似python的方法,并且会起作用。

因为这是有效的,您只需要反馈和建议,您可以考虑将其放到代码审阅站点上。请查看该站点的页面。此问题应在上提出。请用简单的英语解释您的代码正在解决的问题。感谢添加此问题。一个问题是,如果两个数字的组合与目标不匹配,那么程序应该检查其他组合,如3个数字的组合到n个数字的组合,我们如何使其通用
>>> set([x for x in lst for y in lst if x+y == target])