Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

python - 有没有一种简单的方法可以按值删除列表元素?(Is there a simple way to delete a list element by value?)

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print a

The above shows the following error:

(上面显示了以下错误:)

Traceback (most recent call last):
  File "D:zjm_codea.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

So I have to do this:

(所以我必须这样做:)

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print a

But is there not a simpler way to do this?

(但是,没有简单的方法可以做到这一点吗?)

  ask by zjm1126 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To remove an element's first occurrence in a list, simply use list.remove :

(要删除列表中元素的首次出现,只需使用list.remove :)

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

Mind that it does not remove all occurrences of your element.

(请注意,它不会删除所有出现的元素。)

Use a list comprehension for that.

(为此使用列表理解。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...