我试图在Python中编写一个方法,通过查找最小出现次数来查找哪个卡是最稀有的。我也试图返回与这些相关的名称和颜色。有人能帮我写一个更有效的方式吗?我可以计算出现次数,获取颜色并将它们放在列表中,然后在列表中获取名称。但除了把它放在所有单独的列表中之外,我怎么能这样做呢?我可以发布更多代码,但稀有类型是罕见,普通,稀有和神话罕见。
代码:
def get_rarest_card(self):
uncommon_counter = 0
common_counter = 0
rare_counter = 0
mythic_rare_counter =0
mythic_rare_cards=[]
uncommon_color_list=[]
common_color_list=[]
rare_color_list=[]
mythicrare_color_list=[]
for eachCard in self.cardlist:
if eachCard.rarity=="Uncommon":
uncommon_counter = uncommon_counter + 1
uncommon_color_list.append(eachCard.get_colors())
elif eachCard.rarity=="Common":
common_counter=common_counter + 1
common_color_list.append(eachCard.get_colors())
elif eachCard.rarity=="Rare":
rare_counter = rare_counter + 1
rare_color_list.append(eachCard.get_colors())
elif eachCard.rarity=="Mythic Rare":
mythic_rare_cards.append(eachCard.get_name())
mythic_rare_counter = mythic_rare_counter + 1
mythicrare_color_list.append(eachCard.get_colors())
return(mythic_rare_cards)
答案 0 :(得分:0)
collections.Counter
可以帮助您:
from collections import Counter
card_rarities = Counter(card.rarity for card in self.cardlist)
rarity = min(card_rarities, key=lambda card: card_rarities[card]) # Effectively an argmin
return [card for card in self.cardlist if card.rarity == rarity]
任何可以清洗的东西都可以通过这个过程,因此您可以获得最不常见的稀有,颜色或特定卡片,具体取决于您提供给Counter
的内容。
答案 1 :(得分:0)
def get_rarest_cards():
return [card for card in self.cardlist if card.rarity.lower() == 'mythic rare']
如何打印它们取决于您。也许是名字?
mythics = my_cards.get_rarest_cards()
for card in mythics:
print(card.get_name())