【问题标题】:Python - shortening a redundant loopPython - 缩短冗余循环
【发布时间】:2015-05-23 10:37:38
【问题描述】:

如何用 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 提示。

【问题讨论】:

  • 提示:你不需要检查手的长度是否大于零,因为零是假的,所以if len(hand): 做同样的事情。
  • @CarlSmith 除非您可以完全跳过该检查,因为无论如何循环将终止而无需迭代空 hand
  • 好点。我想得更笼统,但是,是的,+1

标签: python if-statement for-loop


【解决方案1】:

您可以使用字典:

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

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

【讨论】:

    【解决方案2】:

    只需将suitcounter 设为字典即可:

    suitcounter_d = {"C":0,"D":0, "S":0 ,"H":0}
    
    for card in hand:
        suitcounter_d[card[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)]
    

    【讨论】:

      【解决方案3】:

      使用集合模块:

      class collections.Counter([iterable-or-mapping]) Counter 是一个字典 用于计算可散列对象的子类。这是一个无序的集合 其中元素存储为字典键,它们的计数是 存储为字典值。计数可以是任何整数 值包括零或负计数。 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})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多