英文:
How to remove the last element from a slice?
问题
我看到有人说可以通过将旧切片追加到新切片来创建一个新的切片:
*slc = append(*slc[:item], *slc[item+1:]...)
但是如果你想删除切片中的最后一个元素呢?
如果你尝试用i+1
替换i
(最后一个元素),会返回一个越界错误,因为不存在i+1
。
英文:
I've seen people say just create a new slice by appending the old one
*slc = append(*slc[:item], *slc[item+1:]...)
but what if you want to remove the last element in the slice?
If you try to replace i
(the last element) with i+1
, it returns an out of bounds error since there is no i+1
.
答案1
得分: 130
你可以使用len()
函数来找到长度,并使用倒数第一个元素之前的索引重新切片:
if len(slice) > 0 {
slice = slice[:len(slice)-1]
}
英文:
You can use len()
to find the length and re-slice using the index before the last element:
if len(slice) > 0 {
slice = slice[:len(slice)-1]
}
<kbd>Click here to see it in the playground</kbd>
答案2
得分: 26
TL;DR:
myslice = myslice[:len(myslice) - 1]
如果myslice
的大小为零,这将失败。
较长的答案:
切片是指向底层数组的数据结构,对切片进行切片等操作会使用相同的底层数组。
这意味着,如果你对一个切片进行切片,新的切片仍然会指向与原始切片相同的数据。
通过上述操作,最后一个元素仍然存在于数组中,但你将无法再引用它。
如果将切片重新切片为原始长度,你将能够引用最后一个对象。
如果你有一个非常大的切片,并且想要修剪底层数组以节省内存,你可能想使用"copy"来创建一个具有较小底层数组的新切片,并让旧的大切片被垃圾回收。
英文:
TL;DR:
myslice = myslice[:len(myslice) - 1]
This will fail if myslice
is zero sized.
Longer answer:
Slices are data structures that point to an underlying array and operations like slicing a slice use the same underlying array.
That means that if you slice a slice, the new slice will still be pointing to the same data as the original slice.
By doing the above, the last element will still be in the array, but you won't be able to reference it anymore.
If you reslice the slice to its original length you'll be able to reference the last object
If you have a really big slice and you want to also prune the underlying array to save memory, you probably wanna use "copy" to create a new slice with a smaller underlying array and let the old big slice get garbage collected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论