如何使用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
=黑桃A。我觉得我做的事情中有太多的代码“垃圾邮件”。 WTB提示。
最佳答案
您可以使用字典:
suitcounter = [0, 0, 0, 0]
suits = {'C': 0, 'D': 1, 'S': 2, 'H': 3}
for card in hand:
suitcounter[suits[card[1]]] += 1
关于python - Python-缩短冗余循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30411661/