[英]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.