2014-08-29 141 views
1

我一直在研究一个项目,我遍历数据列表并删除某些字符前的所有文本。 (这里是一个供参考的例子)Python3.4 for循环迭代问题

>>> myList = ['foo<foo','bar<bar','baz<baz'] 
>>> for element in myList: 
    for char in element: 
     if (char == "<"): 
      break 
     else: 
      charIndex = element.index(char) 
      elementIndex = myList.index(element) 
      print(charIndex, elementIndex) 
      myList[elementIndex] = element[charIndex + 1 :] 
0 0 
Traceback (most recent call last): 
    File "<pyshell#37>", line 7, in <module> 
    elementIndex = myList.index(element) 
ValueError: 'foo<foo' is not in list 
>>> myList 
['oo<foo', 'bar<bar', 'baz<baz'] 
>>> 

对于我未知的原因,元素在重新分配后没有被重命名。
任何帮助将是伟大的,在此先感谢!

回答

1

要设置myList[elementIndex]=

['oo<foo', 'bar<bar', 'baz<baz'] 

myList[elementIndex] = element[charIndex + 1:] # removes f 

element[charIndex + 1:] is from the `first index + 1` so it becomes `'oo<foo'` 

时,如果你把print(element[charIndex + 1 :])在你的循环,你会看到'oo<foo'所以'foo<foo'不会在你的myList中再取出第一个字符,你会得到ValueError

您在for element in myList的第一次迭代中已将element设置为'foo<foo',因此您正在比较原始元素而不是第二个循环中的更新列表元素。

你需要在第二循环中,更新元素的值:

myList[elementIndex] = element[charIndex + 1 :] 
element = element[charIndex + 1 :] 

,输出:

['<foo', '<bar', '<baz'] 

你也可以这样做一个符合列表补偿,这也将如果“<”不在某些字符串中,则工作:

[s[s.index("<"):] if "<" in s else s for s in myList ]