我有一个包含元组的列表,我想用'None'
字符串替换其中一个元组中的None
对象。ValueError迭代Python中的元组列表
这里是我的代码:
x = [('hello','there'),(None,'world',None)]
for i in x:
for j in i:
if j is None:
n = x.index(i)
l = list(x[n])
m = x[n].index(j)
l[m] = 'None'
x[n] = tuple(l)
然而,它抛出的错误:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: (None, 'world', None) is not in list
我如何可以遍历元组适当地与'None'
字符串替换两个None
对象?
元组是不可变的 - 我会建议使用不同的数据结构,如果你需要它是动态的。 – 2014-09-24 18:17:58
这是因为你有两个None,一旦你遇到第一个None,你改变了我的值,但你仍然保存着这个旧的值。例如,它开始为'(None,'world',None)',但当它变成'('None','world',None)时,当它改变时''但是你的i仍然保存着原始值,你用'.index'搜索它没有找到。 – 2014-09-24 18:21:30