如何更新列表中的特定元素?

2024-10-02 04:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

a = ["vishal", 123, 345, "out", 25, "going"] a[2] = 455 a[0] = "dinesh"

我希望索引0和2处的元素会在列表中更新,但我得到的却是TypeError

Traceback (most recent call last):
  File "python", line 15, in <module>
TypeError: 'str' object does not support item assignment

我怎样才能解决这个问题?你知道吗


Tags: 代码元素most列表linecalloutfile
1条回答
网友
1楼 · 发布于 2024-10-02 04:16:51

如果将所有语句都写在同一行中,则语法无效。你知道吗

为此,解决方案1:

a=['vishal',123,345,'out',25,'going']
a[2]=455 
a[0]='dinesh'

现在打印您的列表,您将看到结果:

['dinesh', 123, 455, 'out', 25, 'going']

如果你不想写不同的行,你可以这样做, 解决方案2:

a=['vishal', 123, 345, 'out', 25, 'going']; a[2] =455; a[0]='dinesh'

在语句之间使用分号,这样可以使代码正确运行。你知道吗

相关问题 更多 >

    热门问题