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

计算字典的键,python

  •  0
  • cant_tuna  · 技术社区  · 9 年前

    //编辑-所以我试图找到求和对,但不包括重复对,例如(n1,n2)和(n2,n1)[其中一个被忽略]

    这是我代码的一部分,我想实现的是

    1. 从输入->number\u int split()列表->双循环
    2. count\u dict[sum]=记录多少相同和不同int对的计数记录。

    但我似乎不知道如何正确地增加count变量 请给我建议,谢谢!

    count=1
    for n1 in number_list:
        for n2 in number_list:
    
            sum=n1+n2
    
            if (n2,n1) not in pair_dict and n1!=n2:
                pair_dict[(n1,n2)]=sum
                sum_dict[sum]=(n1,n2)
                if sum_dict[sum]==(n2,n1):
                    count_dict[sum]=count
                else:
                    count+=1
                    count_dict[sum]=count
            else:
                pass
    

    测试用例

    2 1 3 4

    5.

    10 20 40 45 5 15 25

    没有一个

    2 回复  |  直到 9 年前
        1
  •  1
  •   Jared Goguen    9 年前

    从问题的顶部来看,您似乎在试图找到列表中每对元素的总和,并计算每个总和出现的次数。

    from itertools import combinations
    from collections import Counter
    
    number_list = [1, 2, 3, 4, 5]
    sum_counter = Counter(map(sum, combinations(number_list, 2)))
    
    print(sum_counter)
    # {3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1}
    

    通过改变参数,可以很容易地将其推广到计算三元组、四元组等的总和 2 combinations .

        2
  •  -1
  •   Trishant Pahwa    9 年前

    count=1
    for n1 in number_list:
        for n2 in number_list:
    
            sum=n1+n2
    
            if (n2,n1) not in pair_dict and n1!=n2:
                pair_dict[(n1,n2)]=sum
                sum_dict[sum]=(n1,n2)
                if sum_dict[sum]==(n2,n1):
                    count_dict[sum]=count
                else:
                    count+=1
                    count_dict[sum]+=count
            else:
                pass