将变量分配给字符串 - 在保持值的同时打印字符串

时间:2013-11-05 02:12:07

标签: python string variables

这感觉就像一个愚蠢的问题,但我正在消隐一种将字符串转换为int值的方法,然后在打印实际字符串时保留之前分配的值。

我写了一个简单的例子试图解释我在做什么;假设没有相同的值。

unshuffled_list = [2,3,4,5,6,7,8,9,10,'J','Q','K','A']
random.shuffle(unshuffled_list)
aDeck = []
bDeck = []
aDeck = unshuffled_list[0:26]
bDeck = unshuffled_list[26:53]

i = 0

while i <= len(aDeck):
    print("Player A: {}\nPlayer B: {}".format(aDeck[i],bDeck[i]))
    if aDeck[i] > bDeck[i]:
        print("Player A wins!\n")
    if aDeck[i] < bDeck[i]:
        print("Player B wins!\n")
    i += 1

这段代码打破了,没有开玩笑,因为它无法将字符串与int进行比较,但是可以打印出这种类型:

Player A: 9
Player B: Q
Player B Wins!

基本上它会打印出列表中包含的实际字符串,但保留分配给它的int变量。

我通过使用int值列表得到了一段代码,但为了学习,我想知道是否可以这样做。

我还试图搞乱str()和int(),但没有运气。

2 个答案:

答案 0 :(得分:1)

使用字典将指定的卡片映射到其值。

cardValue = { 'J': 11, 'Q': '12', 'K': 13, 'A': 14}
def getCardValue(c)
    return cardValue[c] if c in cardValue else c

while i <= len(aDeck):
    print("Player A: {}\nPlayer B: {}".format(aDeck[i],bDeck[i]))
    cardA = getCardValue(aDeck[i])
    cardB = getCardValue(bDeck[i])
    if  cardA > cardB:
        print("Player A wins!\n")
    elif cardA < cardB:
        print("Player B wins!\n")
    else:
        print("It's a tie!\n")
    i += 1

答案 1 :(得分:0)

不要担心整数与字符串的关系。您可以按原样保留数组,使用混合类型。在任何时候都不需要将字符串转换为整数,反之亦然。

random.shuffle(unshuffled_list)随机播放unshuffled_list。即你丢失了原始的排序顺序。因此,让我们从保留副本开始:

from copy import copy
shuffled_list = copy(unshuffled_list)
random.shuffle(shuffled_list)

然后在代码中将unshuffled_list的所有引用替换为shuffled_list。这也使您的代码更加自我记录。

然后在比较两张牌时,而不是:

if  cardA > cardB:
    ...

这样做:

if unshuffled_list.index(cardA) > unshuffled_list.index(cardB):
    ...

如果unshuffled_list中cardA的索引大于cardB&#34;的索引,则可以将该比较读作&#34;这将是有效的,并且希望很清楚。祝你好运!