2012-11-22 55 views
-1

如何編寫一個函數,根據python計算總點數?如何編寫一個計算python總點數的函數?

例如,

 rank_list=[['Peter','Amy','John','Kitty'],['Amy','John','Kitty','Peter']] 

人們得到5分爲第一等級,2分,爲第二,0點爲第三和9點到最後。

我想要一個清單來計算總人數

回答

3

這是否適合您?

In [277]: rank_list=[['Peter','Amy','John','Kitty'],['Amy','John','Kitty','Peter']] 

In [278]: points = collections.defaultdict(int) 

In [279]: for rank_lis in rank_list: 
    .....:  for score, person in ran 
random  range  rank_list 
    .....:  for score, person in enumerate(rank_lis[::-1]): 
    .....:   points[person] += score 
    .....:   

In [280]: points.items() 
Out[280]: [('Amy', 5), ('John', 3), ('Kitty', 1), ('Peter', 3)] 

一個更有效的解決方案:

In [285]: rank_list=[['Peter','Amy','John','Kitty'],['Amy','John','Kitty','Peter']] 

In [286]: for rank_lis in rank_list: 
    for score, person in enumerate(rank_lis, -3): 
     points[person] -= score 
    .....:   

In [287]: points.items() 
Out[287]: [('Amy', 5), ('Peter', 3), ('Kitty', 1), ('John', 3)] 
+0

+1就像第二個方式:) –

2

您可以使用defaultdict: -

rank_list=[['Peter','Amy','John','Kitty'],['Amy','John','Kitty','Peter']] 
my_dict = {0:3, 1:2, 2:1, 3:0} # Have a mapping from index to score 

from collections import defaultdict 

ranking = defaultdict(int) 

for elem in rank_list: 
    for index, value in enumerate(elem): 
     ranking[value] += my_dict[index] 

print ranking.items() 

OUTPUT: -

[('Amy', 5), ('Kitty', 1), ('Peter', 3), ('John', 3)] 
+0

+1了正確的解決方案,但是,這並不規模。如果有'N >> 3'等級會怎麼樣?你必須寫一個非常大的'my_dict' – inspectorG4dget

+0

@ inspectorG4dget ..是的,在這種情況下,我們必須在繼續之前從'given'字典中創建這個排名字典。但是,你的第二種方式比這更好。 :) –

+0

假設點是線性的(pos 0獲得n個點,pos 1獲得n-1個點,pos n獲得n-n = 0),您可以使用算術而不是字典。 '排名[值] + =(最高分 - 指數)' – Tim

0

我們荷蘭國際集團的反向列表作爲索引(因爲0 = 3,3 = 0,等),並將其保存到一個詞典:

d = {} 
for list in rank_list: 
    for name in list: 
    if name in d: 
     d[name] = d[name] + list[::-1].index(name) 
    else: 
     d[name] = list[::-1].index(name) 

list[::-1]輸出反向列表。另外,您還可以通過打印d['Peter']來獲得分數。

0

它看起來像collections.Counter工作:

from collections import Counter 

rank_list=[['Peter','Amy','John','Kitty'],['Amy','John','Kitty','Peter']] 
rank_by_place = (3, 2, 1, 0) 

ranks = Counter() 
for record in rank_list: 
    for name, rank in zip(record, rank_by_place): 
     ranks.update({name: rank}) 

print ranks.most_common() # ordered by rank 
相關問題