简体   繁体   English

在Python中删除列表的最后一个元素

[英]Removing last element of a list in Python

I've been working on a project in Python, coding a little game that's basically the number version of mastermind. 我一直在用Python开发一个项目,编写一个小游戏,基本上就是mastermind的数字版本。 Anyway, I came across a bug in my program and I'm curious as to why this is: 无论如何,我在程序中遇到了一个错误,我很好奇为什么会这样:

I had a list, and when removing the last element of the list, the order of the remaining elements changed. 我有一个列表,删除列表的最后一个元素时,其余元素的顺序发生了变化。 For example: 例如:

myList = [4, 4, 5, 4]

myList.remove(myList[3])

The contents of the list were now [4, 5, 4] instead of [4, 4, 5] . 列表的内容现在是[4, 5, 4]而不是[4, 4, 5] This did not happen with most other combinations of numbers which is why I am confused. 大多数其他数字组合都没有发生这种情况,这就是我感到困惑的原因。 Also, if I instead use: 另外,如果我改为使用:

myList = myList[:-1]

This works and the contents are in the correct order... Does anyone know why removing the last element the first way didn't work in this case? 这可以正常工作,并且内容按正确的顺序排列...有人知道为什么在这种情况下无法以第一种方式删除最后一个元素吗?

myList.remove(myList[3])

is the same as doing 和做的一样

myList.remove(4)

and remove always removes the first instance. 和remove总是删除第一个实例。 You should try doing: 您应该尝试做:

del a[-1]

or as mentioned by @Megalng 或@Megalng提到

a.pop()

which also returns the removed element 这也返回移除的元素

del myList[-1]

必须爱蟒蛇

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

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