找到列表中的对数

use*_*505 4 python

假设lst = [7,1,5,4,2,3,6],(7, 2), (5, 4), (6, 3)是一些对和总有6个对,加起来 9

(i)一对中的数字顺序很重要.例如,(7,2)和(2,7)是两对不同的对.(ii)数字不能与自身配对.(iii)清单中没有重复的要素

def find_pairs(lst, key):
    count = 0
    if sum(lst[count:count+1]) == key:
        count += 1
        return count
    else:
        return find_pairs(lst[1:],key)  
Run Code Online (Sandbox Code Playgroud)

这是我的代码.怎么了 ??我得到一个错误的输入find_pairs([7,1,5,4,2,3,6], 9)给予6

find_pairs(list(range(1, 100, 2)), 55) #0
find_pairs(list(range(1, 100, 2)), 56) #28
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 5

有一个内置的这个在itertools模块:

def find_pairs(lst, key):
    return [(a,b) for a,b in itertools.permutations(lst, 2) if a+b==key]
Run Code Online (Sandbox Code Playgroud)

或者,更一般地说:

def find_tuples(lst, key, num=2):
    return [i for i in itertools.permutations(lst, num) if sum(i)==key]
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

>>> find_tuples(lst, 9)
[(7, 2), (5, 4), (4, 5), (2, 7), (3, 6), (6, 3)]
>>> find_tuples(lst, 9, 3)
[(1, 5, 3), (1, 2, 6), (1, 3, 5), (1, 6, 2), (5, 1, 3), (5, 3, 1), (4, 2, 3), 
 (4, 3, 2), (2, 1, 6), (2, 4, 3), (2, 3, 4), (2, 6, 1), (3, 1, 5), (3, 5, 1), 
 (3, 4, 2), (3, 2, 4), (6, 1, 2), (6, 2, 1)]
Run Code Online (Sandbox Code Playgroud)

  • 虽然这不给计数,只是列表,需要在末尾或函数中添加``len``. (2认同)