在Python3.2中,如何在列表中追加项目频率的数量?

2024-06-28 11:20:21 发布

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

我是编程新手,python是我学到的第一门语言。在

我想问的问题是如何计算列表中项目的频率 所以它们是按“政党指数”的顺序加起来的?对我来说就是这样。在

这是我需要做的事情的docstring:

''' (list of str) -> tuple of (str, list of int) 
votes is a list of single-candidate ballots for a single riding. 
Based on votes, return a tuple where the first element is the name of the party 
winning the seat and the second is a list with the total votes for each party in 
the order specified in PARTY_INDICES.

>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC']) 
('GREEN', [1, 3, 0, 1])
'''

因为政党指数=[NDP_指数、GREEN_指数、自由党指数、CPC_指数] 这将生成一个获胜方的元组(在本例中为“GREEN”)和 频率,其中[1,3,0,1]

这些是全局变量、列表和字典:

^{pr2}$

这是我的工作:

def voting_plurality(votes):
    my_list = []
    my_dct = {}
    counter = 0
    for ballot in votes:
        if (ballot in my_dct):
            my_dct[ballot] += 1
        else:
            my_dct[ballot] = 1

    if (my_dct):
        my_dct = my_dct.values()
        new_list = list(my_dct)

    return (max(set(votes), key = votes.count), new_list)

返回:

>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC'])
('GREEN', [1, 1, 3])

但我希望它也包括没有投票权的政党,并且符合政党指数[1,3,0,1]

我的代码可能看起来像胡说八道,但我真的被卡住了,很困惑。在

我也不能导入任何东西。在


Tags: oftheinforismygreen指数
1条回答
网友
1楼 · 发布于 2024-06-28 11:20:21

你主要有两个问题。第一个是你必须抓住零,但是由于没有投票给“自由党”,零将不会反映出来。在

提示也许您想初始化字典?在

第二个问题是你打电话来dict.值()不会按任何顺序排列。您需要使用字典和PARTY_INDICES来创建正确排序的数字列表。在

提示也许您可以引用字典中的键以及它们在PARTY_INDICIES列表中各自的位置

看看你能不能想出一些建议,并更新你的问题。如果你做不到,我相信最终会有人发布完整的答案。在

既然已经过去了4个小时,这里有一个解决方案:

def voting_plurality(votes):
    sums = dict(zip(INDEX_TO_NAME.values(), [0] * len(INDEX_TO_NAME)))
    for vote in votes:
        if vote in sums:
            sums[vote] += 1
        else:
            print "Bad vote: %s" % vote
    votes_by_index = sorted([(NAME_TO_INDEX[k], v) for k, v in sums.items()])
    votes_by_rank = sorted(votes_by_index, key=lambda x: x[1], reverse=True)
    votes_by_parts = [item[1] for item in votes_by_index]
    highest_votes = INDEX_TO_NAME[votes_by_rank[0][0]]
    return (highest_votes, votes_by_parts)

相关问题 更多 >