gpt4 book ai didi

python - 为 [字符串]/[列表中的项目] 赋值

转载 作者:行者123 更新时间:2023-11-28 21:48:45 24 4
gpt4 key购买 nike

我正在创建一个纸牌游戏 - blackjack - 并且需要向用户显示一个字符串,但要跟踪每张纸牌在计算中的值(value)。因此,我创建了一个包含卡片所有值的列表:

cards = [1,1,1,1,2,2,2,2,3,3,3,3,...]

但是对于用户来说,例如,如果列表中的项目是 13,我想显示 King。我将如何制作包含这些值的字典/键或数组?我不能使用基于位置的字典,因为发牌后,我会将其从 list/deck 中删除。

最佳答案

您只需定义一个字符串列表:

cardnames = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]

现在如果卡片有值v,你可以用cardnames[v-1]得到对应的名字。例如:

v = 5
print("I have a %s"%cardnames[v-1])

在这种情况下,jack 的值为 11,Queen 为 12,King 为 13。例如(使用 python 的交互式 shell):

$ python
Python 2.7.9 (default, Apr 2 2015, 15:33:21)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> cardnames = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
>>> v=12
>>> print("I have a %s"%cardnames[v-1])
I have a Queen
>>> v=7
>>> print("I have a %s"%cardnames[v-1])
I have a 7
>>> v=1
>>> print("I have a %s"%cardnames[v-1])
I have a Ace
>>> v=13
>>> print("I have a %s"%cardnames[v-1])
I have a King

或者使用python3:

$ python3
Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> cardnames = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
>>> v=12
>>> print("I have a %s"%cardnames[v-1])
I have a Queen
>>> v=7
>>> print("I have a %s"%cardnames[v-1])
I have a 7
>>> v=1
>>> print("I have a %s"%cardnames[v-1])
I have a Ace
>>> v=13
>>> print("I have a %s"%cardnames[v-1])
I have a King

关于python - 为 [字符串]/[列表中的项目] 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34733090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com