是否有一种按值删除列表元素的简单方法?a = [1, 2, 3, 4]b = a.index(6)del a[b]print a上面显示了以下错误:Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in <module> b = a.index(6)ValueError: list.index(x): x not in list所以我必须这么做:a = [1, 2, 3, 4]try: b = a.index(6) del a[b]except: passprint a但是,难道没有更简单的方法来做到这一点吗?
3 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
list.remove
:
>>> a = ['a', 'b', 'c', 'd']>>> a.remove('b')>>> print a['a', 'c', 'd']
>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]>>> a = [x for x in a if x != 20]>>> print a[10, 30, 40, 30, 40, 70]
饮歌长啸
TA贡献1951条经验 获得超3个赞
if c in a: a.remove(c)
try: a.remove(c)except ValueError: pass
千万里不及你
TA贡献1784条经验 获得超9个赞
a=[1,2,3,4]if 6 in a: a.remove(6)
try: a.remove(6)except: pass
添加回答
举报
0/150
提交
取消