从字符串转换后尝试将type(int)插入/更新回嵌套列表时出现Python错误

时间:2019-05-25 02:58:55

标签: python insert int element

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

我绝对是python的新手,并且可以阅读列表理解,在这个阶段,我偏爱“长脚本”,因为它有助于我形象化。

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

我的循环有效,当我$时,我成功打印了需要访问的值。

我可以成功实现所有格式。 capitalised被剥离,单词“ isdigit()”在循环内带有if语句,并且我正在使用string成功地标识int(x)并将其转换为int type is not subscriptable

在我失败的地方,主要是很多尝试将(x)的值插入到我的列表中[3]

我的经验不足吗?

我对它们进行了许多尝试,但是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

不是实际的列表。

TypeError: 'int' object is not subscriptable

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

{{1}}

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您要替换外部列表中的元素,而不是子列表中的元素。当您执行Enumerable#uniq时,即删除了整个子列表。

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

del propertyList[3]

然后更改这些行以修改for sublist in propertyList: x = sublist[3] 而不是sublist

propertyList

但是,只需执行以下操作即可替换元素:

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