# 有一个简单的方法来删除列表元素的值？

``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: pass print a` `

### 17 Solutions collect form web for “有一个简单的方法来删除列表元素的值？”

` `>>> a = ['a', 'b', 'c', 'd'] >>> a.remove('b') >>> print a ['a', 'c', 'd']` `

` `>>> a = [1, 2, 3, 4, 2, 3, 4, 2, 7, 2] >>> a = [x for x in a if x != 2] >>> print a [1, 3, 4, 3, 4, 7]` `

` `if c in a: a.remove(c)` `

` `try: a.remove(c) except ValueError: pass` `

` `a=[1,2,3,4] if 6 in a: a.remove(6)` `

` `try: a.remove(6) except: pass` `

` `a = [1,2,2,3,4,5]` `

` `a = list(filter(lambda x: x!= 2, a))` `

` `a.remove(2)` `

` `def remove_all(seq, value): pos = 0 for item in seq: if item != value: seq[pos] = item pos += 1 del seq[pos:]` `

` `a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4] while a.count(1) > 0: a.remove(1)` `

` `>>> 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` `

IE如果你的数据没有sorting，那么没有重复

` `my_set=set([3,4,2]) my_set.discard(1)` `

` `my_set.add(3)` `

` `a = [1,2,3,1,2,3,4] while True: try: a.remove(3) except: break print a >>> [1, 2, 1, 2, 4]` `

` `c = [1,2,3,4,'x',8,6,7,'x',9,'x'] z = list(set(c) - set(['x'])) print z [1, 2, 3, 4, 6, 7, 8, 9]` `

` `from contextlib import suppress with suppress(ValueError): a.remove('b')` `

` `>>> lst = [23,34,54,45] >>> remove_element = 23 >>> if remove_element in lst: ... lst.pop(lst.index(remove_element)) ... 23 >>> lst [34, 54, 45] >>>` `

` `def cleaner(seq, value): temp = [] for number in seq: if number != value: temp.append(number) return temp` `

` `def cleaner(seq, value, occ): temp = [] for number in seq: if number == value and occ: occ -= 1 continue else: temp.append(number) return temp` `

` `>>> s = [5,4,3,2,1] >>> s[0:2] + s[3:] [5, 4, 2, 1]` `
` ` 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)` `

` `x = [1, 2, 3, 1, 2, 3]` `

` `def Function(List, Unwanted): [List.remove(Unwanted) for Item in range(List.count(Unwanted))] return List x = Function(x, 1) print(x)` `

` `[x.remove(1) for Item in range(x.count(1))] print(x)` `

` `[2, 3, 2, 3, 2, 3]` `

` `import sys a = [1, 2, 3, 4] y = 0 if y < 1: a.remove(1) print len(a) else: sys.exit()` `

• Django模板中的模量％
• pandas：在excel文件中查找表单
• 为什么string切片索引超出范围在Python中工作？
• 如何获得Python类中的方法列表？
• 如何在for循环中修改列表条目？
• subprocess.Popen和os.system之间的区别
• Python SciPy是否需要BLAS？
• ImportError：matplotlib需要dateutil
• Python 3中的相对导入无法正常工作
• 如何离开/退出/停用python virtualenv？
• 使用文件输出自动创build目录