代码之家  ›  专栏  ›  技术社区  ›  CoderCookie10

Python找到至少两个数字的和

  •  -2
  • CoderCookie10  · 技术社区  · 3 年前

    例如,如果我有一个数字列表 [1, 2, 3, 4] ,如何得到一个包含两个或更多数字的字典以及这些数字的总和?我要找的理想词典如下所示:

    num = [1, 2, 3]
    ideal_dict = {[1,2]:3, [1, 3]:4, [1, 4]:5, [2, 3]:5, [2, 4]:6, [3, 4]:7, [1, 2, 3]:6, [2, 3, 4]:9, [1, 2, 3, 4]:10}
    

    [5, 3, 4, 8, 9] .

    谢谢你的时间和考虑。

    2 回复  |  直到 3 年前
        1
  •  2
  •   Parth Patel    3 年前

    这就是你要找的吗?它有两个for循环,一个嵌入到另一个中,遍历列表并添加数字,然后添加到字典中。

    # original number list
    numbers = (1,3,24,53,3565,474,23,2,546,27,578, 76,976)
    
    # target dictonary
    dict = {}
    
    for i in range(len(numbers)):
        for j in range(len(numbers)):
            value = numbers[i] + numbers[j]
            dict[(i,j)] = value
    
    
    print(dict)
    
        2
  •  1
  •   Chris Charley    3 年前
        3
  •  0
  •   CoderCookie10    3 年前

    您可以使用itertools的组合,如下所示:

    from itertools import combinations
      
    def combo(arr, r):
        return list(combinations(arr, r))
    
    arr = [1, 2, 3, 4]
    r = [2, 3, 4]
    for rr in r:
        print (combo(arr, rr))
    

    输出:

    [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
    [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
    [(1, 2, 3, 4)]