【问题标题】:Delete item in a list in Python [duplicate]在Python中删除列表中的项目[重复]
【发布时间】:2015-03-05 13:58:54
【问题描述】:

如何在 Python 中只查找和删除列表中的一个元素?

# Example:deleting only the first (1,2) in the list
a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
# result expected
a = [(4, 5), (7, 5), (1, 2), (5, 2)]

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    使用list.remove() 方法就地删除第一个匹配项:

    a.remove((1, 2))
    

    演示:

    >>> a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
    >>> a.remove((1, 2))
    >>> a
    [(4, 5), (7, 5), (1, 2), (5, 2)]
    

    Mutable Sequence Types documentation

    s.remove(x)
    del s[s.index(x)]

    s.index() 只会找到第一个匹配项。

    【讨论】:

    • 非常感谢!!!!!!!!!!!!!!!!!!!!!!!!!!!祝福。
    【解决方案2】:

    您好,如果您想删除列表中的任何内容

    使用这些代码

    mylist.pop(element_order) #mylist stands for your list and
    #element_order stands for the order of element is the list and if it is the 
    #first element it will be 0
    

    或者你可以使用

    mylist.remove(the_element)
    

    请注意,在 pop 中它是一个方法而不是一个列表

    mylist.pop(0)
    print mylist
    

    不要使用

    mylist = mylist.pop(0)
    

    【讨论】:

    • 列表没有 delete 方法。 mylist.pop() 按索引 删除元素,而不是按值,这是 OP 所要求的,并且还返回删除的元素,使其比简单的 del listobject[index] 做得更多。
    • 对不起,我的意思是删除
    猜你喜欢
    • 2011-09-29
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多