在Python中,如何为包含字符串的列表中的元素分配整数?

时间:2017-11-11 22:09:28

标签: python list

    ## made a list of playing cards e.g. 2C 2 of Clubs and QS is queen of Spades
    num=0
    numberlist=[]
    newSuitList= []
    for i in range(8):
        num = 2
        num = num + i
        num = str(num) + 'C'
        numberlist.append(num)
    for i in range (5):
        suitList = ["T", "J", "Q", "K", "A"]
        suit = suitList[i] + 'C'
        newSuitList.append(suit)
    wholeDeck = numberlist+newSuitList
制作牌组后,我想为每张牌分配一个值  黑桃王(价值13)的价值高于 例如,黑桃皇后(12)。我无法弄明白该怎么做。

2 个答案:

答案 0 :(得分:0)

由于您的目标是将卡与值相关联,因此您希望使用字典(如评论所述)。这是一个不会改变你的代码的实现,可以帮助你:

num=0
wholeDeck = {}
for i in range(8):
    num = 2
    num +=  i
    wholeDeck[str(num)+'C']  = num
suitList = ["T", "J", "Q", "K", "A"]
for item in suitList:
    num +=1
    wholeDeck[item+'C']  = num

因此,您可以访问这样的卡片,

print(wholeDeck['KC']) --> returns 13

答案 1 :(得分:0)

另一种使用列表的简单方法:

cards = ['A', 2, 3 , 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']

def getCardValue(card):
  return cards.index(card) + 1

然后getCardvalue('Q')将返回值12