我是編程新手,python是我學過的第一門語言。如何在Python 3.2的列表中添加項目頻率的數量?
我想問的問題是如何計算列表 中的項目的頻率,以便按照「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]
我的代碼可能看起來像無稽之談,但我真的stu克和困惑。
另外我不能IMPORT什麼。
你爲什麼不準進口什麼? –
我想這是作業。解釋爲什麼OP在編寫該方法和施加的限制之前具有完整的文檔字符串。 – BoppreH