如何从Scala列表中删除一个项目只有其索引? [英] How to remove an item from a list in Scala having only its index?
问题描述
我有一个如下列表:
val internalIdList:List [Int] = List()
internalIdList = List(11,12,13,14,15)
删除第三个元素,以获得:
internalIdList = List(11,12,14,15)
我不能使用 ListBuffer
,有义务保持现有结构体。
我该怎么办?
感谢所有
<如果你知道你将会删除第三个元素(索引2),那么你可以简单地使用
val trunced = internalIdList.take(2)++ internalIdList.drop(3)
否则,如果您不事先知道要删除的元素的索引是什么,你可以写一个如下的函数:
$ b $ $ $ $ $ $ $ $ $ $ def defIndex(ix :Int)= if(internalIdList.size< ix)internalIdList
else internalIdList.take(ix)++ internalIdList.drop(ix + 1)
I have a list as follows:
val internalIdList: List[Int] = List()
internalIdList = List(11, 12, 13, 14, 15)
From this list would remove the third element in order to obtain:
internalIdList = List(11, 12, 14, 15)
I can not use a ListBuffer
, are obliged to maintain the existing structure.
How can I do?
Thanks to all
If you know that you will be dropping the third element (index 2), then you can simply use
val trunced = internalIdList.take(2) ++ internalIdList.drop(3)
otherwise, if you don't know beforehand what the index will be of the element to remove, you could write a function like the following:
def removeIndex(ix: Int) = if (internalIdList.size < ix) internalIdList
else internalIdList.take(ix) ++ internalIdList.drop(ix+1)
这篇关于如何从Scala列表中删除一个项目只有其索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!