如何使用4个冗余if语句缩短此循环?
此代码旨在计算每个套装在纸牌游戏中玩牌的数量:
suitcounter = [0, 0, 0, 0]
if len(hand) > 0:
for card in hand:
if card[1] == "C":
suitcounter[0] += 1
if card[1] == "D":
suitcounter[1] += 1
if card[1] == "S":
suitcounter[2] += 1
if card[1] == "H":
suitcounter[3] += 1
return suitcounter
手由两颗心和一条铁锹组成:
>>>hand = ['3H', '4H', 'AS']
[0, 0, 1, 2]
3H
= 3颗心,4H
= 4颗心,AS
=黑桃王牌。
我觉得有太多的代码和垃圾邮件'在我所做的事情中。 WTB提示。
答案 0 :(得分:5)
您可以使用字典:
suitcounter = [0, 0, 0, 0]
suits = {'C': 0, 'D': 1, 'S': 2, 'H': 3}
for card in hand:
suitcounter[suits[card[1]]] += 1
答案 1 :(得分:3)
只需要suitcounter
dict:
suitcounter_d = {"C":0,"D":0, "S":0 ,"H":0}
for card in hand:
suitcounter_d[card[1]] += 1
检查长度也是多余的,好像它是< 1将没有循环。
如果您想要输出一些订单,请使用OrderedDict:
from collections import OrderedDict
suitcounter_d = OrderedDict((('C', 0), ('D', 0), ('S', 0), ('H', 0)))
for card in hand:
suitcounter_d[card[1]] += 1
所以把它放在你的函数中并像你的例子一样返回很简单,只需访问dict值:
from collections import OrderedDict
def suit_out(hand):
suit_count_dict = OrderedDict((('C', 0), ('D', 0), ('S', 0), ('H', 0)))
for card in hand:
suit_count_dict[card[1]] += 1
return list(suit_count_dict.values())
print(suit_out(['3H', '4H', 'AS']))
[0, 0, 1, 2]
如果您使用.items,您将获得套装/计数配对作为元组中的输出:
return list(suit_count_dict.items())
print(suit_out(['3H', '4H', 'AS']))
[('C', 0), ('D', 0), ('S', 1), ('H', 2)]
答案 2 :(得分:2)
使用集合模块:
class collections.Counter([iterable-or-mapping])
计数器是一个词典 用于计算可哈希对象的子类。这是一个无序的集合 其中元素存储为字典键,其数量是 存储为字典值。计数允许为任何整数 值包括零或负数。 Counter类是类似的 用其他语言的包或多重集。
import collections
def count_suites(cards):
suits = (card[1] for card in cards)
return collections.Counter(suits)
以类似的方式,您可以按值计算卡片:
import collections
def count_values(cards):
values = (card[0] for card in cards)
return collections.Counter(values)
样本用法和输出:
cards = ['3H', '4H', 'AS']
print count_suites(cards) # Counter({'H': 2, 'S': 1})
print count_values(cards) # Counter({'A': 1, '3': 1, '4': 1})