我有以下清单:
x = [['0_1 1_0']]
我想用0替换0_1。
这是我已经尝试过的:
x[0].replace("0_1", "0")
但后来我收到以下错误:
AttributeError: 'list' object has no attribute 'replace'
它应该是:
x[0][0] = x[0][0].replace("0_1", "0")
以来:
>>> x = [['0_1 1_0']]
>>> x
[['0_1 1_0']]
>>> x[0]
['0_1 1_0']
>>> x[0][0]
'0_1 1_0'
>>> x[0][0] = x[0][0].replace("0_1", "0")
>>> x
[['0 1_0']]
因为字符串是不可变的,所以你不能就地更改它们,但必须重新分配它。
由于在执行x [0]时有一个2D列表,因此您可以访问列表中的列表。 x [0] [0] .replace(“0_1”,“0”)也是如此
因此,您需要了解可以使用替换功能的生态系统。例如,如果有一个字符串I want to replace string operation properly
,你想用replace
替换learn
那就是它的工作原理。
string = "I want to replace string operation properly"
new_string = string.replace("replace", "learn")
在您的情况下,字符串项位于嵌套列表中。首先,您需要访问嵌套列表中的项目:
test_list = [["foo_1"], ["foo_1"], ["bar_2"], ["soo_2"]]
new_list = []
for item in test_list: # iterate through the list and fix it
print("Actual:", item[0])
print("Replaced:", item[0].replace("foo", "who"))
new_list.append(item[0].replace("foo", "who"))
您已将列表定义到列表中,因此,您需要提供两个索引来访问在您的情况下写为块“0_1 1_0”的信息。因此,您必须更改整个块,而不仅仅是您想要的“0_1”。
x[0][0] = '0' #--> will generate x = [['0']].
另一种选择是逐个元素地定义一个列表:
x = ['0_1','1_0']
然后,您可以通过提供相应的索引来替换内容
x[0] = '0'
我希望它有效。
最好的祝福
Ramir