繁体   English   中英

Python-> TypeError:列表索引必须是整数,而不是str

[英]Python -> TypeError: list indices must be integers, not str

我在python中有一个列表/数组str4 ,我想使用一个我坚信是int的变量来访问它,因为我用isdigit()函数对其进行了测试,并且还进行了手动调试,并检查了所有选项是否都出来正确地用唯一的数字。

temp = "variableX"
file2 = open('file.txt','r')
for line in file2:
  if line.find(temp) =! -1:
    posArray = line.split(temp)[1][1:3]
    if ")" in posArray:
      posArray = posArray[:-1]
    if posArray.isdigit():
      num = posArray
      print temp+"("+num+")"
      print num
      print str4[num]

上面的代码用于调试,我的问题是在str4 [num]中 ,上面的代码的结果是:

variableX(1)
1
"this is position 1"
Traceback (most recent call last):
  File "orderList.py", line34, in <module>
    print str4[num]
TypeError: list indices must be integers, not str

为什么num是一个数字,但是python告诉我它是一个字符串? 我究竟做错了什么?

您检查了字符串posArray是否为数字:

  if posArray.isdigit():
      num = posArray

但是您没有将其转换为数字,如下所示:

  if posArray.isdigit():
      num = int(posArray)

看看下面带有我的评论的代码。 从头到尾阅读它,以了解如何轻松调试自己的代码; 思维过程是什么。

temp = "variableX"
file2 = open('file.txt','r')  # which is a file, so `line` is `string` - CASE CLOSED
for line in file2:  # and `line` is a result of looping through `file2`
  if line.find(temp) =! -1:
    posArray = line.split(temp)[1][1:3]  # and `posArray` is a part of `line`
    if ")" in posArray:
      posArray = posArray[:-1]  # ok, `posArray` is a part of `posArray`
    if posArray.isdigit():  # `posArray` contains digits only but that doesn't help really, so does "123"..
      num = posArray  # ok, so `num` is whatever `posArray` is
      print temp+"("+num+")"
      print num
      print str4[num]  # here is the Error so we start here and work backwards

上面我们显示的是,最终num将与linestr )具有相同的类型,因此,不能将其用于index任何内容。 必须先通过int(num)将其转换为int

口译员永远不会错...

更严重的是,您将num作为子字符串,因此它是一个字符串。 如果要将其用作字符串索引,则必须将其转换为int:

  num = int(posArray)          # ok num is now an int
  print temp+"("+str(num)+")"  # must use str to concat it with strings
  print num, type(num), posArray, type(posArray) # num is int, posArray is string
  print str4[num]              # now fine

另一个解决方案是

num = posArray

做:

print str4[int(num)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM