繁体   English   中英

如果列表中包含列表中的最后一个数字,如何删除列表中的最后一个数字

[英]how to remove the last digit in a list if the list contain number last number some were in the list

我需要删除给定列表中的一个数字,但是在执行此第一个数字时会被删除

python pycharm

l = [4, 2, 6, 4, 7]

l.remove(l[3])

print(l)

预期输出: [4, 2, 6, 7]但是我得到: [2, 6, 4, 7]

要从给定索引的列表中删除项目,请像这样使用list().pop()

l.pop(3)  # Remove the third element.

它有3种方法从python List中删除一个元素。

您可以在此处阅读有关list更多信息

list.pop(3)   # remove 4th element

del list(3)   # remove 4th element

list.remove(value1)  # remove element have value1 in list

如果您的列表是动态生成的,请避免使用直接pop()函数,因为您不知道元素的index

enumerate()函数向可迭代对象添加一个计数器。 因此,对于游标中的每个元素,都使用(counter, element)生成一个元组。

list1 = [4, 2, 6, 4, 7]
new_list = []
for index,elm in enumerate(list1):
    if elm not in (list1[:index]):
        new_list.append(elm)

print(new_list)

O / P:

[4, 2, 6, 7]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM