我用它来删除列表中的非字母字符
alphabet = -1
int(alphabet)
while alphabet != howlong:
alphabet = alphabet + 1
print alphabet
if ldata[alphabet] == "a":
print "a"
elif ldata[alphabet] == "b":
print "b"
elif ldata[alphabet] == "c":
print "c"
elif ldata[alphabet] == "d":
print "d"
elif ldata[alphabet] == "e":
print "e"
elif ldata[alphabet] == "f":
print "f"
elif ldata[alphabet] == "g":
print "g"
elif ldata[alphabet] == "h":
print "h"
elif ldata[alphabet] == "i":
print "i"
elif ldata[alphabet] == "j":
print "j"
elif ldata[alphabet] == "k":
print "k"
elif ldata[alphabet] == "l":
print "l"
elif ldata[alphabet] == "m":
print "m"
elif ldata[alphabet] == "n":
print "n"
elif ldata[alphabet] == "o":
print "o"
elif ldata[alphabet] == "p":
print "p"
elif ldata[alphabet] == "q":
print "q"
elif ldata[alphabet] == "r":
print "r"
elif ldata[alphabet] == "s":
print "s"
elif ldata[alphabet] == "t":
print "t"
elif ldata[alphabet] == "u":
print "u"
elif ldata[alphabet] == "v":
print "v"
elif ldata[alphabet] == "w":
print "w"
elif ldata[alphabet] == "x":
print "x"
elif ldata[alphabet] == "y":
print "y"
elif ldata[alphabet] == "z":
print "z"
else:
#deletes non letter and all of the same things from the list
z = ldata[alphabet]
ldata = [x for x in ldata if x != z]
它达到57742元素,然后列表索引超出范围。我计算了清单,它超越了它。这也不是pythons列表中最大可能的元素数量。我很困惑,想知道是否有任何我可能错过的东西。请在星期一帮助这个:(。如果有更简单的方法可以做到这一点,我会非常感谢。
答案 0 :(得分:0)
<强>更新强>
错误来自于您在迭代时从列表中删除的事实。纠正这种情况的最佳方法如下:
new_list = [char for char in ldata if "a" <= char <= "z"]
每次删除项目时,都可以通过递减howlong
来更正此方法。
您可以执行以下操作,这应该避免列表索引超出范围问题:
for char in ldata:
if "a" <= char <= "z":
print(char)
通过使用for-each样式循环,您将遍历列表中的每个条目。这将确保您到达每个项目,而不会使您的索引超出范围。
完全赞同@ DYZ建议使用if "a" <= ldata[alphabet] <= "z": print(ldata[alphabet])
作为for循环的内部部分!