python - 从字符串转换后尝试将类型(int)插入/更新回嵌套列表时出现 Python 错误
问题描述
我需要访问和转换从 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 元素替换字符串元素。
TypeError: 'int' object is not subscriptable
解决方案
我认为您的问题是您要替换外部列表中的元素,而不是子列表。当您这样做del propertyList[3]
时,即删除整个子列表。
要从子列表中删除,您需要为子列表和列表中的元素使用单独的变量名,所以从这样开始:
for sublist in propertyList:
x = sublist[3]
然后将这些行更改为修改sublist
而不是propertyList
:
del propertyList[3]
propertyList.insert(3, x)
但是,仅通过执行以下操作替换元素要简单得多:
sublist[3] = x
推荐阅读
- javascript - 未提供查询参数时的默认 GraphQL 服务器字符串响应?
- c# - ASP.NET:如何避免动态创建按钮事件刷新页面而不是做相关代码的情况
- time-complexity - O(n) 和 O(log n) 的乘积是多少?
- swift - ARKit - 具有相似图像但颜色不同的图像识别
- pandas - 如何根据它们的数量删除数据框中的大量列?
- typescript - 使用仅类型导入会使我的打字稿文件超级冗长和混乱——它们真的需要吗?
- java - 从 csv 文件(如 Arraylist.add)向列表添加元素
- nginx - 如何使用一个 ssl 设置 nginx 多个应用程序和多个端口
- python - 实现 Selenium 以使用更改的身份验证代理
- ios - 基于设备方向的 Deep ArView 更新帧输出