首页 > 解决方案 > 从字符串转换后尝试将类型(int)插入/更新回嵌套列表时出现 Python 错误

问题描述

我需要访问和转换从 txt 文件创建的嵌套列表中的元素 3。

我是 python 的新手,可以阅读列表理解,在这个阶段我偏爱“长脚本”,因为它可以帮助我进行可视化。

元素是字符串类型。它包含一个我必须大写的单词或一个数字以及$要删除的符号。

我的循环有效,当我print(x)成功打印出我需要访问的值时。

我可以成功实现所有格式。$被剥离,这个词capitalised在循环中带有一个 if 语句,我正在使用isdigit()它来成功识别并转换stringint(x).

在我失败的地方,主要是多次尝试获取 (x) 的值并将其插入我的列表 [3]

是我缺乏经验吗?

我在它们上尝试了很多变化,但主要的错误int type is not subscriptable困扰着我。

我的理解是列表是可变的并且可以容纳各种类型,对吗?

这是我的代码。

del list[3]
list.insert(3, x)
list[3] = x
if list[3] !='':
    list[3] = x

不是实际列表。

propertyList = [[ some , text , 23424], [other , 3234 , replaceme],[text, floatreplace, 99.33]] 
for x in propertyList:
  x = x[3]
  x = x.strip('$')

  try:
    if "." in x :
      x = float(x)
      print(x, "Yes, user input is a float number.")
    elif(x.isdigit()):
      x = int(x)
      del propertyList[3]
      propertyList.insert(3, x)
      print(x, "Yes, input string is an Integer.")
    else:
     if x == 'auction':
      x = x.capitalize()
      print(x)
  except ValueError:
    print(x, 'is type',type(x))
# propertyList[3].replace(x)
print(propertyList)

return

我希望用我的新格式化和转换的 int 元素替换字符串元素。

TypeError: 'int' object is not subscriptable

标签: pythoninsertintelement

解决方案


我认为您的问题是您要替换外部列表中的元素,而不是子列表。当您这样做del propertyList[3]时,即删除整个子列表。

要从子列表中删除,您需要为子列表和列表中的元素使用单独的变量名,所以从这样开始:

for sublist in propertyList:
    x = sublist[3]

然后将这些行更改为修改sublist而不是propertyList

del propertyList[3]
propertyList.insert(3, x)

但是,仅通过执行以下操作替换元素要简单得多:

sublist[3] = x

推荐阅读