如何从列表中获取元素对的总和

2024-10-01 07:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单lst = [2, 4, 5, 6, 7, 8]

  • 如果我在搜索12,我的输出应该是(4,8),(5,7)
  • 我的当前输出仅显示(4,8)
  • 如果我正在打印报税表,那么列表的背面也会打印(4,8),(5,7), (8,4)、(7,5)
def find_sum(s, lst):
    indices = {x: i for i, x in enumerate(lst)}
#     print(indices)
    for i, x in enumerate(lst):
        target = s - x
        if target in indices:
            return (lst[i], lst[indices[target]])

    return None

lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst)) 

应为(4,8), (5,7)


Tags: innonetarget列表forreturnifdef
3条回答

您已经得到了几个其他答案,但只是为了好玩,使用递归:

def find_sum(s, lst):
    if len(lst) <= 1: # with list of length <= 1, impossible to find a pair
        return []
    x, sublst = lst[0], lst[1:]
    if s - x in sublst:
        return [(x, s - x)] + find_sum(s, sublst)
    else:
        return find_sum(s, sublst)

lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst)) # [(4, 8), (5, 7)]

在每个递归步骤中,给定一个列表,我们选择head元素(命名为x)和列表的其余部分sublst。如果在sublst中有一个元素与x求和以得到给定的数字,则返回x和其他内容。这是递归发生的地方;我们只考虑了(x, y)ysublst中的(x, y)对,而不是sublst中的^对。所以我们需要再次调用find_sum,使用这个sublst。当给定列表的长度为1或为空时,该递归过程结束;在这些情况下,没有配对要考虑,所以只返回一个空列表。

注意这里的else是多余的,因为它前面有return。但我还是喜欢它在那里


以下是使用生成器的另一个版本:

def find_sum(s, lst):
    lst = lst.copy()
    while lst:
        x = lst.pop(0)
        if s - x in lst:
            yield x, s - x

lst = [2, 4, 5, 6, 7, 8]
print(list(find_sum(12, lst))) # [(4, 8), (5, 7)]

试试这个:

import itertools

def find_sum(s, lst):
    return [x for x in itertools.combinations(lst, r=2) if x[0] + x[1] == s]

lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst))

输出

[(4, 8), (5, 7)]

当您调用return时,您正在结束函数。这意味着一旦你找到第一对,你的函数就结束了,你再也找不到了

要解决这个问题,您应该在名为good_pairs(或任何您想要的)的函数中添加一个数组。与其写return (lst[i], lst[indices[target]]),不如写good_pairs.append((lst[i], lst[indices[target]]))

最后,只需返回good_pairs列表

然后用你想要的格式打印出来

最终代码:

def find_sum(s, lst):
    s.sort()
    good_pairs = []
    indices = {x: i for i, x in enumerate(lst[:len(lst)//2])}
    # print(indices)
    for i, x in enumerate(lst):
        target = s - x
        if target in indices:
            good_pairs.append((lst[i], lst[indices[target]]))

    return good_pairs

lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst)) 

我首先对数组进行排序,然后仅枚举数组的一半以防止重复。归功于@enzo

希望这有帮助,祝你好运:)

相关问题 更多 >