【问题标题】:How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x如何根据字符串列表的元组字典的第一个索引添加值?蟒蛇 3x
【发布时间】:2012-11-26 22:57:37
【问题描述】:

我不知道如何正确地制定这个问题,以下是:

如果我们有以下值会怎样:

{('A','B','C','D'):3, 
('A','C','B','D'):2,
('B','D','C','A'):4,
('D','C','B','A'):3,
('C','B','A','D'):1,
('C','D','A','B'):1}

当我们总结第一名的值时:[5,4,2,3](5 人先选 A,4 人先选 B,依此类推,如 A = 5, B = 4, C = 2, D = 3)

任何字母表的最大值都是 5,这不是多数(5/14 小于一半),其中 14 是总值的总和。

因此,我们删除了第一名最少的字母表。在这种情况下是 C。

我想返回一个字典,其中{'A':5, 'B':4, 'C':2, 'D':3} 不导入任何东西。

这是我的作品:

def popular(letter):
    '''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
    '''
    my_dictionary = {}
    counter = 0

    for (alphabet, picks) in letter.items():
        if (alphabet[0]):
            my_dictionary[alphabet[0]] = picks
        else:
            my_dictionary[alphabet[0]] = counter

    return my_dictionary

这会返回我无法删除的重复键。

谢谢。

【问题讨论】:

标签: python key tuples dictionary


【解决方案1】:

以下应该有效:

def popular(letter):
    '''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
    '''
    my_dictionary = {}
    for alphabet, picks in letter.items():
        if alphabet[0] in my_dictionary:
            my_dictionary[alphabet[0]] += picks
        else:
            my_dictionary[alphabet[0]] = picks
    return my_dictionary

例子:

>>> letter = {('A','B','C','D'):3, 
... ('A','C','B','D'):2,
... ('B','D','C','A'):4,
... ('D','C','B','A'):3,
... ('C','B','A','D'):1,
... ('C','D','A','B'):1}
>>> popular(letter)
{'A': 5, 'C': 2, 'B': 4, 'D': 3}

这可以使用collections.defaultdict 更简洁地完成:

from collections import defaultdict
def popular(letter):
    my_dictionary = defaultdict(int)
    for alphabet, picks in letter.items():
        my_dictionary[alphabet[0]] += picks
    return dict(my_dictionary)

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    相关资源
    最近更新 更多