2012-11-22 13 views
0

我是編程新手,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什麼。

+0

你爲什麼不準進口什麼? –

+0

我想這是作業。解釋爲什麼OP在編寫該方法和施加的限制之前具有完整的文檔字符串。 – BoppreH

回答

0

您有兩個主要問題。首先是你必須捕捉到零,但由於沒有對「自由黨」進行投票,零不會被反映出來。

提示也許你想初始化你的字典?

第二個問題是你正在調用dict.values(),它不會以任何順序。您需要使用字典,並使用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) 
相關問題