开发者

how to remove multiple duplicates from a list?

I'm trying to write a program that plays a game of go fish between two players and i currently stuck trying to remove the duplicates in the first hand dealt.

This is the code i have so far, and it only removes one dupe. I was wondering if anyone can help me enhance it by allowing to remove all dupes

#sorts player1 cards and removes the pairs
player1.sort()
print "hand for player 1:"
print cards.hand_string(player1)
newplayer1 = []
player1points = 0

newplayer1, player1points = cards.drop_pair(player1)
print cards.hand_string(newplayer1)

s=spades d=diamonds h=hearts c=clu开发者_开发知识库bs

for this game a player will get 8 cards each for ex TS TD JH QS QC AC AD AH

my code results in this JH QS QC AC AD AH i want it to result in this JH AH

thank you in advance


If the ordering does not matter: use a set() or dict() instead. Otherwise you have to iterate over the whole list and remove items from the list. Or you maintain the ordered list and keep track of the unique items in the list through a second dict. Before inserting a new item to the list you check first if the item exists already in side the dict - this is adviceable for large list - perhapse overkill for small lists.


Use sets. http://docs.python.org/library/stdtypes.html#set


You could call that function that removes one dupe again and again until there are no dupes left.


So as I see it the suit does not matter in matching. unique_hand_values = [h[0] for h in hands] gets a list of all of the card values (no suit).

From there you can loop and compare since they are sorted in order:

for index, hand_value in enumerate(unique_hand_values): 
    if index + 1 < len(hand_value) and hand_value == unique_hand_values[index + 1]:
        # its a duplicate


from itertools import groupby
from operator import itemgetter

player1 = ['TS', 'TD', 'JH', 'QS', 'QC', 'AC', 'AD', 'AH']
new_player1 = []

groups = groupby(player1, key=itemgetter(0))
for key, group in groups:
    group = list(group)
    if len(group)%2:
        new_player1.append(group[-1])

print new_player1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜