Compare position of a specfic item from an old to a new list

时间:2018-03-25 21:15:18

标签: python list

I have a list in python on the same form as the following:

list = [["player1", "team1", "pointsPlayer1"],["player2", "team2", "pointsPlayer2"]]

The list contains between 0 and 20 players.

My problem is that I want to be able to know how many places each player gains or loses after new points are given (after a round). I know I'll have to make a copy of the list before points are given and then compare it to the updated list, but I don't know how to do that.

2 个答案:

答案 0 :(得分:0)

你写的是numpy数组的等价结构,它基本上是一个列表列表,我建议你使用numpy数组。我不知道你的意思是什么,但这是一个小片段,我很快写下来给你一个想法。对你起作用吗? (假设数组完全是int)类型

import numpy as np

players = np.zeros((20,3), dtype=int)

def get_gains(points): # also numpy array
    gains_dict = {}
    for i, point in enumerate(points):
        current_points = players[i][2]
        gain = current_points + point
        gains_dict[players[i][0]] = gain
        current_points = gain
    return gains_dict

答案 1 :(得分:0)

collections.Counter是执行此类任务的有用工具。它不清楚您的输入和所需输出的确切含义,但下面是您应该能够适应的示例。

from collections import Counter

c = Counter()

# ROUND 1
c.update({'player1': 40, 'player2': 20, 'player3': 30})
# Counter({'player1': 40, 'player2': 40, 'player3': 60})

order1 = {k: idx for idx, (k, _) in enumerate(c.most_common())}
# {'player1': 0, 'player2': 2, 'player3': 1}

# ROUND 2
c.update({'player1': 10, 'player2': 40, 'player3': 15})
# Counter({'player1': 50, 'player2': 60, 'player3': 45})

order2 = {k: idx for idx, (k, _) in enumerate(c.most_common())}
# {'player1': 1, 'player2': 0, 'player3': 2}

# CHANGE IN ORDER
change = {k: order2[k] - order1[k] for k in c}
# {'player1': 1, 'player2': -2, 'player3': 1}