【问题标题】:Match list indices with strings to create a working deck of cards将列表索引与字符串匹配以创建工作卡组
【发布时间】:2020-05-16 14:53:59
【问题描述】:

这是学校作业。我有一个从 0 到 51 的列表,代表一副纸牌。我的目标是制作一个功能,允许用户输入从 0 到 51 的数字,并且每个数字都将匹配一副牌中的一张卡片。例如,如果数字 0 代表方块 A,1 代表方块 2,依此类推... 每 14 个数字,花色应更改为下一个数字。这是我目前所拥有的:

deck = list(range(52))

def cardid(card_num):
        suits = ["diamonds", "hearts", "clubs", "spades"]
        cards = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack","queen", "king"]

我一直在尝试将数字与卡片匹配。分配说明建议使用地板除法和除法余数,但这不需要很多 if 语句吗?还有另一种(更简单)的方法吗?请记住我刚刚开始使用python。

【问题讨论】:

    标签: python list function


    【解决方案1】:

    其实很简单。您需要两个索引,一个对应于花色列表,另一个对应于卡片列表。以下是获取它们的方法:

    def cardid(card_num):
        suits = ["diamonds", "hearts", "clubs", "spades"]
        cards = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack","queen", "king"]
        suits_index = int(card_num/13) # Here's your floor division
        cards_index = card_num%13      # And here's your division remainder 
        print ("The card is",cards[cards_index],"of",suits[suits_index])
    

    要验证,只需调用函数如下:

    card_num = int(input("Enter a number: "))
    # Just to make sure the input is valid for the scope of this function
    if card_num >=0 and card_num < 52:
        cardid(card_num)
    

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 1970-01-01
      • 2014-01-09
      • 2021-08-08
      • 2019-01-05
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多