我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
上面给出了错误:
ValueError: list.index(x): x not in list
所以我必须这样做:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
难道没有更简单的方法吗?
我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
上面给出了错误:
ValueError: list.index(x): x not in list
所以我必须这样做:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
难道没有更简单的方法吗?
当前回答
在列表中查找一个值,然后删除该索引(如果它存在的话),使用list的remove方法更容易完成:
>>> a = [1, 2, 3, 4]
>>> try:
... a.remove(6)
... except ValueError:
... pass
...
>>> print a
[1, 2, 3, 4]
>>> try:
... a.remove(3)
... except ValueError:
... pass
...
>>> print a
[1, 2, 4]
如果你经常这样做,你可以把它包在一个函数中:
def remove_if_exists(L, value):
try:
L.remove(value)
except ValueError:
pass
其他回答
在列表中查找一个值,然后删除该索引(如果它存在的话),使用list的remove方法更容易完成:
>>> a = [1, 2, 3, 4]
>>> try:
... a.remove(6)
... except ValueError:
... pass
...
>>> print a
[1, 2, 3, 4]
>>> try:
... a.remove(3)
... except ValueError:
... pass
...
>>> print a
[1, 2, 4]
如果你经常这样做,你可以把它包在一个函数中:
def remove_if_exists(L, value):
try:
L.remove(value)
except ValueError:
pass
你可以这样做
a=[1,2,3,4]
if 6 in a:
a.remove(6)
但以上需要在list a中搜索2次6,所以尝试except会更快
try:
a.remove(6)
except:
pass
list1=[1,2,3,3,4,5,6,1,3,4,5]
n=int(input('enter number'))
while n in list1:
list1.remove(n)
print(list1)
arr = [1, 1, 3, 4, 5, 2, 4, 3]
# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)
# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]
# if you want to delete a position use "pop" function, suppose
# position 4
# the pop function also returns a value
removed_element = arr.pop(4)
# u can also use "del" to delete a position
del arr[4]
这将从数组sys中删除"-v"的所有实例。Argv,如果没有找到实例,则不报错:
while "-v" in sys.argv:
sys.argv.remove('-v')
你可以在一个名为speechToText.py的文件中看到代码的运行:
$ python speechToText.py -v
['speechToText.py']
$ python speechToText.py -x
['speechToText.py', '-x']
$ python speechToText.py -v -v
['speechToText.py']
$ python speechToText.py -v -v -x
['speechToText.py', '-x']