简体   繁体   English

python,列出元组,找到连续的数字

[英]python, list with tuples, find consecutive numbers

The title is kind of misleading, but I can't really describe it in one line. 标题有点令人误解,但我无法真正描述它。

I have a list that looks like this. 我有一个看起来像这样的清单。

a = [(4, 2), (4, 3), (2, 1), (1, 0), (1, 4)]

The list was already sorted by the first term of the tuple, using this code. 使用此代码,该列表已按元组的第一项排序。

a.sort( key = lambda x: x[0], reverse = True )

(I am just saying that the list is already sorted, so there's no need to sort) (我只是说列表已经排序,因此无需排序)

Assume that the first term of the tuple is the score of a Poker player, and second term is the name of each Poker player. 假定元组的第一项是扑克玩家的分数,第二项是每个扑克玩家的名字。 So, the list above is the same as this: 因此,上面的列表与此相同:

[ ( score = 4, player 2 ), ( score = 4, player 3 ), (score = 2, player 1 ), (score = 1, player 0), (score = 1, player = 4) ] [(分数= 4,玩家2),(分数= 4,玩家3),(分数= 2,玩家1),(分数= 1,玩家0),(分数= 1,玩家= 4)]

There are 5 players, and the score of each players could be the same, or different. 有5个玩家,每个玩家的得分可以相同或不同。

I want to evaluate the players based on their score, and want to print result in case of ties (when . So, 我想根据他们的得分来评估球员,并希望在出现平局的情况下打印结果(因此,

Player 2 ties
Player 3 ties

Player 0 ties
Player 4 ties

Player 2 and 3 had the same score (score = 4) and they tied. 玩家2和3得分相同(得分= 4),并列并列。 Also, Player 0 and 4 ties, but since their score ( score = 1) was lower than that of Player 2 and 3, they were printed below player 2 and 3. 同样,玩家0和4并列,但由于他们的得分(得分= 1)低于玩家2和3,因此它们被打印在玩家2和3下方。

How can I do this in Python? 如何在Python中执行此操作?

This is a problem tailor-made for itertools.groupby : 这是为itertools.groupby量身定制的问题:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> L = [(4, 2), (4, 3), (2, 1), (1, 0), (1, 4)]
>>> for key, group in groupby(L, itemgetter(0)):
...     group = list(group)
...     if len(group) > 1:
...         for k, player in group:
...             assert k == key
...             print(f'Player {player} ties')
...         print()
...         
Player 2 ties
Player 3 ties

Player 0 ties
Player 4 ties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM