-1

如何在python中编写一个计算总分的函数?

例如,

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

第一名得5分,第二名得2分,第三名得0分,最后一名得9分。

我想要一个计算人总点数的列表

4

4 回答 4

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)]
于 2012-11-22T06:27:19.040 回答
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()

输出 : -

[('Amy', 5), ('Kitty', 1), ('Peter', 3), ('John', 3)]
于 2012-11-22T06:32:54.473 回答
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'],例如。

于 2012-11-22T06:39:08.290 回答
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
于 2012-11-22T06:39:27.043 回答