我想从数组中删除单词sabin,但它显示出一些错误......
array=["sabin","ram","hari","sabin"]
length=len(array)
for steps in range(length):
if(array[steps]=="sabin"):
print("removed=%s"%(array[steps]))
del array[steps]
length=len(array)
print(length)
答案 0 :(得分:0)
你可以用列表复制来做到这一点:
array=["sabin","ram","hari","sabin"]
length=len(array)
array = [x for x in array if not x == 'sabin']
length=len(array)
答案 1 :(得分:0)
您收到的错误是IndexError。这是因为您正在从列表中删除值,同时仍在迭代它。一种可能的解决方案是使用list对象的remove方法来删除" sabin"的实例:
array=["sabin","ram","hari","sabin"]
to_remove = 'sabin'
while to_remove in array:
array.remove(to_remove)
print("removed=%s"%(to_remove))
print(len(array))
这可以避免IndexError,因为它不依赖于索引在整个循环中保持不变。
答案 2 :(得分:0)
您也可以使用filter!
my_list = ["sabin","ram","hari","sabin"]
print(my_list)
>>> ['sabin', 'ram', 'hari', 'sabin']
my_list = filter(lambda x: x != 'sabin', my_list)
print(my_list)
>>> ['ram', 'hari']