简体   繁体   中英

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) ]

There are 5 players, and the score of each players could be the same, or different.

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. 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.

How can I do this in Python?

This is a problem tailor-made for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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