Leo Asked:2020-02-17 22:31:52 +0000 UTC2020-02-17 22:31:52 +0000 UTC 2020-02-17 22:31:52 +0000 UTC 计算列表中部分匹配的元素 772 给定:“手牌”列表(模拟游戏)。列表项表示为字符串,例如:“6♡”或“10♣”。 问题:如何正确识别重复面额的牌,即只考虑丢弃的最后一个字符表示花色的行?这样结果就显示为一个对象,其中元素按重复的降序排列。已经有一个 getnominal(card) 函数可以打印面额的数值。脑海中只想到了一个单独的列表,其中只有教派,但似乎这种方法太文盲了。 python 1 个回答 Voted Best Answer gil9red 2020-02-17T22:40:38Z2020-02-17T22:40:38Z 有一个清单: items = ['4♣', '4♡', '6♡', '10♣', '9♣'] 按花色和按面值计算: number = sum(1 for x in items if '♣' in x) print(number) # 3 number = sum(1 for x in items if '4' in x[:-1]) print(number) # 2 按花色和面额降序排列: new_items = sorted(items, key=lambda x: (x[-1], int(x[:-1])), reverse=True) print(new_items) # ['10♣', '9♣', '4♣', '6♡', '4♡'] 按花色分组,其中花色是关键,值是具有该花色的卡片列表: from collections import defaultdict suit_by_card = defaultdict(list) for x in items: suit = x[-1] suit_by_card[suit].append(x) print(suit_by_card) # {'♣': ['4♣', '10♣', '9♣'], '♡': ['4♡', '6♡']} 与上面类似,只有面额是关键: value_by_card = defaultdict(list) for x in items: value = int(x[:-1]) value_by_card[value].append(x) print(value_by_card) # {'4': ['4♣', '4♡'], '6': ['6♡'], '10': ['10♣'], '9': ['9♣']} 使用Counter列出重复项的示例: from collections import Counter items = ['4♣', '4♡', '9♣', '4♡', '6♡', '4♡', '10♣', '9♣'] card_by_number = Counter(items) print(card_by_number) # {'4♡': 3, '9♣': 2, '4♣': 1, '6♡': 1, '10♣': 1} duplicates = [k for k, v in card_by_number.items() if v > 1] print(duplicates) # ['4♡', '9♣'] UPD。 from collections import defaultdict items = ['6♠', '9♠', '9♡', '10♢', '13♠', '13♡', '13♢', '14♣'] value_by_card = defaultdict(list) for x in items: value = int(x[:-1]) value_by_card[value].append(x) print(value_by_card) # {6: ['6♠'], 9: ['9♠', '9♡'], 10: ['10♢'], 13: ['13♠', '13♡', '13♢'], 14: ['14♣']} order_nums = [] nums = sorted(value_by_card.keys(), reverse=True) for num in nums: cards = value_by_card[num] print(cards) order_nums.append(cards) # ['14♣'] # ['13♠', '13♡', '13♢'] # ['10♢'] # ['9♠', '9♡'] # ['6♠'] print(order_nums) # [['14♣'], ['13♠', '13♡', '13♢'], ['10♢'], ['9♠', '9♡'], ['6♠']] PS。 x[-1]-- 返回最后一个字符10♣->♣ x[:-1]-- 这将返回除最后一个字符之外的所有内容10♣->10
有一个清单:
按花色和按面值计算:
按花色和面额降序排列:
按花色分组,其中花色是关键,值是具有该花色的卡片列表:
与上面类似,只有面额是关键:
使用Counter列出重复项的示例:
UPD。
PS。
x[-1]-- 返回最后一个字符10♣->♣x[:-1]-- 这将返回除最后一个字符之外的所有内容10♣->10