在Python中,字符串索引必须是整数

2024-05-27 11:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python来解决一个竞赛问题。我得到了这个错误。我对Python相当陌生,也没有经验。在

    for kek in sorteddic:
        lengthitem = int(len(kek))
        questionstring = start[0, lengthitem]

kek本质上是“sorteddic”中的“item”,它是一个字符串数组。在

我得到的错误是:

^{pr2}$

有人能帮忙吗?谢谢。在


Tags: 字符串inforlen错误经验itemstart
2条回答

这是因为要用作索引的项0, lengthitem不是整数,而是整数的元组,如下所示:

>>> x = 1 : type(x)
<class 'int'>
>>> x = 1,2 : type(x)
<class 'tuple'>

如果您的目的是获取数组的一部分(不是完全的清除,但我保证这是一个相当安全的猜测),那么正确的运算符是:,如:

^{pr2}$

或者,由于0是默认起点:

questionstring = start[:lengthitem]

下面的脚本显示了当前代码段是如何失败的以及如何正确地执行此操作:

>>> print("ABCDE"[1])
B

>>> print("ABCDE"[1,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

>>> print("ABCDE"[1:3])
BC

切片表示法使用冒号,而不是逗号(除非您在numpy中,其中逗号分隔了切片中的维度,尽管它被视为切片对象的元组)。所以使用:

questionstring = start[0:lengthitem]

相关问题 更多 >

    热门问题