冗余的Python循环缩短

2024-04-25 14:47:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何用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

示例:

手由两个心和一个黑桃组成:

^{pr2}$

3H=3颗红桃,4H=4颗红桃,AS=黑桃的Ace。在

我觉得我做的事情中有太多的“垃圾邮件”。WTB提示。在


Tags: 代码in游戏for数量lenif玩家
3条回答

使用集合模块:

class collections.Counter([iterable-or-mapping]) A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

import collections

def count_suites(cards):
    suits = (card[1] for card in cards)
    return collections.Counter(suits)

用同样的方法,你可以按价值计算牌数:

^{pr2}$

示例使用和输出:

cards = ['3H', '4H', 'AS']
print count_suites(cards)  # Counter({'H': 2, 'S': 1})
print count_values(cards)  # Counter({'A': 1, '3': 1, '4': 1})

你可以使用字典:

suitcounter = [0, 0, 0, 0]
suits = {'C': 0, 'D': 1, 'S': 2, 'H': 3}

for card in hand:
    suitcounter[suits[card[1]]] += 1

只需做suitcounter一段口述:

suitcounter_d = {"C":0,"D":0, "S":0 ,"H":0}

for card in hand:
    suitcounter_d[card[1]] += 1

另外,检查长度是多余的,就好像它是<;1一样,不会有循环。在

如果要对输出进行排序,请使用OrderedDict

^{pr2}$

因此,将其放入函数中并按示例返回很简单,只需访问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,您将得到一个suit/count对作为tuples的输出:

return list(suit_count_dict.items())
print(suit_out(['3H', '4H', 'AS']))

[('C', 0), ('D', 0), ('S', 1), ('H', 2)]

相关问题 更多 >

    热门问题