2014-09-24 77 views
-2

我有一个包含元组的列表,我想用'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对象?

+0

元组是不可变的 - 我会建议使用不同的数据结构,如果你需要它是动态的。 – 2014-09-24 18:17:58

+2

这是因为你有两个None,一旦你遇到第一个None,你改变了我的值,但你仍然保存着这个旧的值。例如,它开始为'(None,'world',None)',但当它变成'('None','world',None)时,当它改变时''但是你的i仍然保存着原始值,你用'.index'搜索它没有找到。 – 2014-09-24 18:21:30

回答

1

第一None值后更改为'None',j仍然是(None, 'world', None)。您正在更新x[n],但不是j。如果您直接通过x进行迭代,则您的代码有效。

x = [('hello','there'),(None,'world',None)] 
for i in range(len(x)): 
    for j in x[i]: 
     if j is None: 
      n = i 
      l = list(x[n]) 
      m = x[n].index(j) 
      l[m] = 'None' 
      x[n] = tuple(l) 
+0

感谢@MackM对解决方案的解释和想法 – Daniel 2014-09-24 18:45:29

2
>>> x = [('hello', 'there'),(None, 'world', None)] 
>>> [tuple('None' if item is None else item for item in tup) for tup in x] 
[('hello', 'there'), ('None', 'world', 'None')] 
2

你找到None当你第一次运行

x[n] = tuple(l) 

改变(None,'world',None)('None','world',None)。你会发现None第二次运行

x.index((None,'world',None)) 

但现在x是

x = [('hello','there'),('None','world',None)] 

所以它不包含(None,'world',None),产生你的值错误

+0

谢谢@pqnet这帮了很大的忙! – Daniel 2014-09-24 18:41:00