如何从Scala列表中删除一个项目只有其索引? [英] How to remove an item from a list in Scala having only its index?

查看:155
本文介绍了如何从Scala列表中删除一个项目只有其索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下列表:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆