【问题标题】:how to remove multiple duplicates from a list?如何从列表中删除多个重复项?
【发布时间】:2013-09-26 04:03:15
【问题描述】:

我正在尝试编写一个在两个玩家之间玩围棋游戏的程序 我目前一直在尝试删除第一手交易中的重复项。

这是我到目前为止的代码,它只删除了一个欺骗。我想知道是否有人可以通过允许删除所有欺骗来帮助我增强它

#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=黑桃 d=钻石 h=心 c=俱乐部

对于这个游戏,玩家每人将获得 8 张牌作为前任 TS TD JH QS QC AC AD AH

我的代码导致了这个 JH QS QC AC AD AH 我希望它导致这个 JH啊

提前谢谢你

【问题讨论】:

  • 你为什么要AH?您如何选择哪些 A 不是配对的?还是你真的只想要 JH?

标签: python list


【解决方案1】:

如果排序无关紧要:使用 set() 或 dict() 代替。否则,您必须遍历整个列表并从列表中删除项目。或者您维护有序列表并通过第二个字典跟踪列表中的唯一项目。在将新项目插入列表之前,您首先检查该项目是否已经存在于字典中 - 这对于大列表是建议的 - 对于小列表来说可能是矫枉过正。

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      您可以调用该函数一次又一次地删除一个欺骗,直到没有任何欺骗。

      【讨论】:

        【解决方案4】:

        所以在我看来,西装在搭配上并不重要。 unique_hand_values = [h[0] for h in hands] 获取所有牌值的列表(无花色)。

        从那里你可以循环和比较,因为它们是按顺序排序的:

        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
        

        【讨论】:

          【解决方案5】:
          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-02-20
            • 2019-12-07
            • 2018-05-16
            • 2016-04-18
            • 1970-01-01
            • 2023-03-05
            相关资源
            最近更新 更多