简体   繁体   English

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

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

i need to remove a digit in the given list,But while executing this first digit is removed 我需要删除给定列表中的一个数字,但是在执行此第一个数字时会被删除

python pycharm python pycharm

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

l.remove(l[3])

print(l)

expected output: [4, 2, 6, 7] But I get: [2, 6, 4, 7] 预期输出: [4, 2, 6, 7]但是我得到: [2, 6, 4, 7]

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

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

It has 3 methods to remove an element from python List. 它有3种方法从python List中删除一个元素。

You can read more about list in here 您可以在此处阅读有关list更多信息

list.pop(3)   # remove 4th element

del list(3)   # remove 4th element

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

Avoid using a direct pop() function if your list is dynamically generating because you don't know the index of elements. 如果您的列表是动态生成的,请避免使用直接pop()函数,因为您不知道元素的index

The enumerate() function adds a counter to an iterable. enumerate()函数向可迭代对象添加一个计数器。 So for each element in a cursor, a tuple is produced with (counter, element) . 因此,对于游标中的每个元素,都使用(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: O / P:

[4, 2, 6, 7]

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

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