ValueError:list.remove(x):x不在列表中,在for循环中抛出

时间:2015-08-21 10:40:53

标签: python

每次我尝试运行此程序时,python都会抛出错误ValueError: list.remove(x): x not in list

def symmetric_words(wlist):

alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25}
symmetric = []

for word in wlist:
    if len(word) % 2 == 0:
        symmetric.append(word)

for item in symmetric:
    for i in range(0,int(len(item)/2)-1):          
        if alphabet.get(item[i])!=(25-alphabet.get(item[len(item)-(i+1)])):
            symmetric.remove(item)

  return symmetric

print(symmetric_words(["neither", "a", "borrower", "nor", "a", "lender", "be"]))

该程序应该将单词列表作为输入并测试它们是否对称(它们的第一个字母和最后一个字母与它们各自的字母表末端的距离相同等等),它的工作原理对于输入列表["boy", "dog", "bevy", "bully"]很好,bevy是对称的,但不适用于输入["neither", "a", "borrower", "nor", "a", "lender", "be"],或者我尝试过的其他几个,而不是抛出上述错误。 我已经尽可能多地阅读,并且我相信它是因为当python再次从对称词列表中删除它时已经删除了一个值,但我无法为我的生活做好准备弄清楚如何解决它。

该程序首先要检查每个单词的长度是偶数还是奇数,因为没有奇数加长的单词可能是对称的,然后将偶数加长的单词添加到对称列表中。然后将对称列表发送到2个嵌套for循环,这些循环旨在删除任何不符合要对称的单词的位置要求的单词,这是错误发生的位置(第10行,symmetric.remove(item)语句)。 我很抱歉,如果这是一个愚蠢的问题,我对一般的编程非常陌生,感谢提前或任何所有的帮助。

2 个答案:

答案 0 :(得分:1)

在这一点:

for i in range(0,int(len(item)/2)-1):          
    if alphabet.get(item[i])!=(25-alphabet.get(item[len(item)-(i+1)])):
        symmetric.remove(item)

您检测到字符串不对称并将其从对称列表中删除,但随后继续循环并继续检查它,因此它将尝试一遍又一遍地删除相同的字符串。删除字符串后尝试打破内部循环。

答案 1 :(得分:0)

我建议从列表中删除元素,同时迭代它们将是一个坏主意。相反,您可以使用all()方法检查所有左侧字符是否与正确的字符匹配(根据您的条件),然后如果所有这些字符都正确,则将其附加到新列表。代码 -

def symmetric_words(wlist):
    alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25}
    ret = []
    for item in wlist:
        if len(item) % 2 == 0:
            if all(alphabet.get(item[i])==(25-alphabet.get(item[len(item)-(i+1)])) for i in range(len(item)//2)):
                    ret.append(item)
    return ret

示例/演示 -

>>> def symmetric_words(wlist):
...     alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25}
...     ret = []
...     for item in wlist:
...             if len(item) % 2 == 0:
...                     if all(alphabet.get(item[i])==(25-alphabet.get(item[len(item)-(i+1)])) for i in range(len(item)//2)):
...                                     ret.append(item)
...     return ret
...
>>> print(symmetric_words(["boy", "dog", "bevy", "bully"]))
['bevy']
>>> print(symmetric_words(["neither", "a", "borrower", "nor", "a", "lender", "be"]))
[]