我是编程新手,python 是我学习的第一门语言。
我想问的问题是如何计算列表中项目的频率,以便它们按“PARTY_INDICES”的顺序加起来?就我而言,就是这样。
这是我需要做的文档字符串:
''' (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])
'''
由于 PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX] 这会产生获胜方的元组(在本例中为“GREEN”)和频率列表,其中 [1, 3, 0, 1]
这些是全局变量、列表和字典:
# The indices where each party's data appears in a 4-element list.
NDP_INDEX = 0
GREEN_INDEX = 1
LIBERAL_INDEX = 2
CPC_INDEX = 3
# A list of the indices where each party's data appears in a 4-element list.
PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]
# A dict where each key is a party name and each value is that party's index.
NAME_TO_INDEX = {
'NDP': NDP_INDEX,
'GREEN': GREEN_INDEX,
'LIBERAL': LIBERAL_INDEX,
'CPC': CPC_INDEX
}
# A dict where each key is a party's index and each value is that party's name.
INDEX_TO_NAME = {
NDP_INDEX: 'NDP',
GREEN_INDEX: 'GREEN',
LIBERAL_INDEX: 'LIBERAL',
CPC_INDEX: 'CPC'
}
这是我的工作:
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])
但我希望它也包括没有投票的政党,并且符合 PARTY_INDICES [1, 3, 0, 1]
我的代码可能看起来像胡说八道,但我真的很困惑。
我也不能导入任何东西。