如何遍历字符串列表?

时间:2016-04-02 10:43:26

标签: python-3.x

我有这段代码:

test = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]

for i in test:
    if i not in ["C","D"]:
        test.remove(i)

print(test)

由于运行上面的代码,我希望得到['C','D'],但是我得到了['B', 'C', 'D', 'F', 'H', 'J', 'L', 'N']

如何成功遍历字符串列表并删除使用Python 3不需要的元素?

注意:我不想使用理解列表

感谢

2 个答案:

答案 0 :(得分:3)

从其他语言的列表中删除时,我曾经反向走过列表:

test = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]

for i in reversed(test):
    if i not in ["C","D"]:
        test.remove(i)

print(test)

请注意reversed会创建一个新列表,因此这可能不是大型列表的最佳解决方案。现在,既然你已经走了一份列表副本,如果你需要按照正确的顺序解析,你可以使用copy

import copy
for i in copy.copy(test):
    if i not in ["C","D"]:
        test.remove(i)

并避免导入(来自here):

for i in test[:]:
    if i not in ["C","D"]:
        test.remove(i)

最后,对我来说最好的解决方案是传统的,就地反向迭代而不复制列表(“借用”并修改自this答案)

for i in range(len(test) - 1, -1, -1):
    if test[i] not in ["C","D"]:
        del test[i]

答案 1 :(得分:0)

第一个循环:i ='A',i不在['C','D'] - >删除i。现在test的第一项是'B'。所以在下一个循环i将等于'C'。这就是出问题的地方......