[英]String Indices Must be Integers in Python
I am using Python to solve a contest problem. 我正在使用Python解决竞赛问题。 I am getting this error.
我收到此错误。 I am fairly new and inexperienced with Python.
我是新手,对Python经验不足。
for kek in sorteddic:
lengthitem = int(len(kek))
questionstring = start[0, lengthitem]
kek is essentially the "item" in "sorteddic" which is an array of strings. kek本质上是“ sorteddic”中的“ item”,它是字符串的数组。
The error I am getting is: 我得到的错误是:
questionstring = start[0, lengthitem]
TypeError: string indices must be integers
Can someone please help? 有人可以帮忙吗? Thanks.
谢谢。
It's because the item you're trying to use as an index, 0, lengthitem
, is not an integer but a tuple of integers, as shown below: 这是因为您要用作索引的项目
0, lengthitem
不是整数,而是一个整数元组 ,如下所示:
>>> x = 1 : type(x)
<class 'int'>
>>> x = 1,2 : type(x)
<class 'tuple'>
If your intent is to get a slice of the array (not entirely clear but I'd warrant it's a fairly safe guess), the correct operator to use is :
, as in: 如果您打算获取数组的一部分(虽然不完全清楚,但我保证这是一个相当安全的猜测),则使用的正确运算符是
:
,如下所示:
questionstring = start[0:lengthitem]
or, since 0
is the default start point: 或,因为
0
是默认起点:
questionstring = start[:lengthitem]
The following transcript shows how your current snippet fails and the correct way to do it: 以下文字记录显示了您当前的代码片段失败的方式以及正确的处理方式:
>>> 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
Slice notation uses colons , not commas (unless you are in numpy
where commas separate dimensions in slices, athough under the hood that is treated as a tuple of slice objects). 切片符号使用冒号 ,而不是逗号 (除非您在
numpy
中逗号分隔切片中的维度,尽管在引擎盖下被视为切片对象的元组)。 So use: 因此使用:
questionstring = start[0:lengthitem]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.