Py学习  »  Python

从字符串转换后,试图将类型(int)插入/更新回嵌套列表时出现python错误

Adrian Juhl • 6 年前 • 221 次点击  

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

我对python是个新手,可以阅读列表理解,在这个阶段,我更喜欢“长脚本”,因为它可以帮助我可视化。

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

我的循环工作,当我 print(x) 我得到了我需要访问的值的成功打印。

我可以成功地实现所有格式设置。 $ 被剥去,这个词是 capitalised 循环中有一个if语句,我正在使用 isdigit() 成功识别和转换 string int(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元素替换string元素。

TypeError: 'int' object is not subscriptable

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38278
文章 [ 1 ]  |  最新文章 6 年前
mapeters
Reply   •   1 楼
mapeters    7 年前

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

要从子列表中删除,需要为子列表和列表中的元素使用一个单独的变量名,因此从下面开始:

for sublist in propertyList:
    x = sublist[3]

然后更改这些行进行修改 sublist 而不是 propertyList :

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

但是,仅通过这样做就可以更简单地更换元件:

sublist[3] = x