好的,这可能类似于这个主题:Finding 4 highest values from an array
但我不知道如何使用2d列表这样做,所以这是我的问题: 我有一个清单:
teams = [Randomteam1,Randomteam2,Randomteam3,Randomteam4,Randomteam5,Randomteam6]
和2d列表:
team_info = [[7, 2, 1, 1, 3], [4, 1, 1, 1, 3],[2, 0, 2, 2, 3], [12, 3, 0, 0, 3]],
[9, 0, 2, 2, 3], [10, 3, 0, 0, 6]]
在该列表中,每个例如,[7,2,1,1,3]是团队得分的信息,7是多少分,2多少胜利,1失败,1抽奖,3是游戏播放。 team_info中的每个块都与团队中的一个团队相关联。例如:
Randomteam1 = [7, 2, 1, 1, 3], Randomteam2 = [4, 1, 1, 1, 3]
依旧......
现在我希望得到/显示得分最高的前4支球队,以及最低得分的前2支球队。
答案 0 :(得分:2)
我可能已经使用过dict但是你可以将列表压缩在一起然后进行排序:
teams = ["Randomteam1","Randomteam2","Randomteam3","Randomteam4","Randomteam5","Randomteam6"]
team_info = [[7, 2, 1, 1, 3], [4, 1, 1, 1, 3],[2, 0, 2, 2, 3], [12, 3, 0, 0, 3], [9, 0, 2, 2, 3], [10, 3, 0, 0, 6]]
data = sorted(zip(teams,team_info),key= lambda x: x[1][0],reverse=True)
[('Randomteam4', [12, 3, 0, 0, 3]), ('Randomteam6', [10, 3, 0, 0, 6]), ('Randomteam5', [9, 0, 2, 2, 3]), ('Randomteam1', [7, 2, 1, 1, 3]), ('Randomteam2', [4, 1, 1, 1, 3]), ('Randomteam3', [2, 0, 2, 2, 3])]
结果是团队按照最高得分的顺序排序,排序键为x[1][0]
,这是每个配对中第二个元素的第一个元素,即每个团队的总分数。
前4名将是data[:4]
,后两队将是data[-2:]
如果您使用dict,将很容易关联团队并访问任何团队 他们的数据,你可以将团队和数据存储为一个字典,并使用排名作为关键:
data = {}
srt = sorted(zip(team_info, teams), reverse=True,1)
for ind, (b,a) in enumerate(srt):
p, w, l, d, gp = b
data["rank_{}".format(ind)] = {"team":a,"points": p, "wins": w, "loss": l, "draw": d, "games": gp}
from pprint import pprint as pp
pp(data)
输出:
{'rank_1': {'team': 'Randomteam4',
'draw': 0,
'games': 3,
'loss': 0,
'points': 12,
'wins': 3},
'rank_2': {'team': 'Randomteam6',
'draw': 0,
'games': 6,
'loss': 0,
'points': 10,
'wins': 3},
'rank_3': {'team': 'Randomteam5',
'draw': 2,
'games': 3,
'loss': 2,
'points': 9,
'wins': 0},
'rank_4': {'team': 'Randomteam1',
'draw': 1,
'games': 3,
'loss': 1,
'points': 7,
'wins': 2},
'rank_5': {'team': 'Randomteam2',
'draw': 1,
'games': 3,
'loss': 1,
'points': 4,
'wins': 1},
'rank_6': {'team': 'Randomteam3',
'draw': 2,
'games': 3,
'loss': 2,
'points': 2,
'wins': 0}}
答案 1 :(得分:1)
您可以对列表进行排序,并使用简单的切片获取元素:
zip
如果您想要团队名称,也可以使用>>> sorted(zip(teams,team_info),key=itemgetter(1,0),reverse=True)[:4]
[('Randomteam4', [12, 3, 0, 0, 3]), ('Randomteam6', [10, 3, 0, 0, 6]), ('Randomteam5', [9, 0, 2, 2, 3]), ('Randomteam1', [7, 2, 1, 1, 3])]
>>>
>>> zip(*sorted(zip(teams,team_info),key=itemgetter(1,0),reverse=True)[:4])[0]
('Randomteam4', 'Randomteam6', 'Randomteam5', 'Randomteam1')
:
heapq.nlargest
您还可以使用nsmallest
和>>> import heapq
>>> heapq.nlargest(4,team_info,key=itemgetter(0))
[[12, 3, 0, 0, 3], [10, 3, 0, 0, 6], [9, 0, 2, 2, 3], [7, 2, 1, 1, 3]]
>>> heapq.nsmallest(2,team_info,key=itemgetter(0))
[[2, 0, 2, 2, 3], [4, 1, 1, 1, 3]]
来获取N个最大和最小的元素:
Email_Password+oi8hu907b;New_eMail+Y;Email_Username+iugbhijhb8