在 python 3 中的索引内转换字符串切片
Converting the slice of a string inside an index in python 3
对于一个学校项目,我必须制作一个二十一点游戏,长话短说,我的部分手牌评估代码涉及我通过切片列表选择的字符串切片来递增变量。
我的代码是:
player_hand_sum =+ int(player_hand[0[:0]])
Which returns a 'int' object is not subscriptable 错误。
关于如何补救这个问题有什么想法吗?
TIA
编辑:"player_hand" 是一个包含两到五个字符串的列表。
问题来自切片内部 -
0[:0]
您正在尝试在此处下标 0
,这会引发 int
不可下标错误。显示相同错误的示例 -
>>> l = [1,2]
>>> l[0[:0]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
您想改为 [0][:1]
,例如 -
player_hand_sum += int(player_hand[0][:1]])
此外,另一个问题,=+
(尽管语法有效)不会将左侧名称的值增加到右侧的名称(它只是直接分配),以增加你需要使用 +=
.
对于一个学校项目,我必须制作一个二十一点游戏,长话短说,我的部分手牌评估代码涉及我通过切片列表选择的字符串切片来递增变量。
我的代码是:
player_hand_sum =+ int(player_hand[0[:0]])
Which returns a 'int' object is not subscriptable 错误。
关于如何补救这个问题有什么想法吗?
TIA
编辑:"player_hand" 是一个包含两到五个字符串的列表。
问题来自切片内部 -
0[:0]
您正在尝试在此处下标 0
,这会引发 int
不可下标错误。显示相同错误的示例 -
>>> l = [1,2]
>>> l[0[:0]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
您想改为 [0][:1]
,例如 -
player_hand_sum += int(player_hand[0][:1]])
此外,另一个问题,=+
(尽管语法有效)不会将左侧名称的值增加到右侧的名称(它只是直接分配),以增加你需要使用 +=
.