我如何习惯性地“删除"邮件?从Scala中的列表中选择一个元素并缩小差距? [英] How can I idiomatically "remove" a single element from a list in Scala and close the gap?

查看:309
本文介绍了我如何习惯性地“删除"邮件?从Scala中的列表中选择一个元素并缩小差距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表在Scala中是不可变的,因此我试图弄清楚如何删除"(实际上是创建一个新集合)该元素,然后缩小在列表中创建的间隔.在我看来,这将是一个使用地图的好地方,但我不知道如何开始使用该地图.

Lists are immutable in Scala, so I'm trying to figure out how I can "remove" - really, create a new collection - that element and then close the gap created in the list. This sounds to me like it would be a great place to use map, but I don't know how to get started in this instance.

课程是一个字符串列表.我需要这个循环,因为我实际上有几个列表,我需要从中删除该索引处的元素(我使用多个列表来存储跨列表关联的数据,而我只是通过确保索引始终对应于列表).

Courses is a list of strings. I need this loop because I actually have several lists that I will need to remove the element at that index from (I'm using multiple lists to store data associated across lists, and I'm doing this by simply ensuring that the indices will always correspond across lists).

  for (i <- 0 until courses.length){
    if (input == courses(i) {
    //I need a map call on each list here to remove that element
    //this element is not guaranteed to be at the front or the end of the list
    }
  }
}

让我为这个问题添加一些细节.我有四个通过索引相互关联的列表.一个列表存储课程名称,一个列表以简单的int格式(即130)存储课程开始的时间,一个列表存储"am"或"pm",以int形式存储课程的日期(因此"MWF"等于1,"TR"等于2,依此类推.我不知道这是解决这个问题的最佳方法还是正确"的方法,但是这些都是我所拥有的工具(自从16岁以来就没有认真编程过的一年制计算机科学专业的学生).我正在编写一个从每个列表中删除相应元素的函数,我所知道的是1)索引对应,2)用户输入课程名称.如何使用filterNot从每个列表中删除相应的元素?我认为我对每个列表都不了解,无法在其上使用高阶函数.

Let me add some detail to the problem. I have four lists that are associated with each other by index; one list stores the course names, one stores the time the class begins in a simple int format (ie 130), one stores either "am" or "pm", and one stores the days of the classes by int (so "MWF" evals to 1, "TR" evals to 2, etc). I don't know if having multiple this is the best or the "right" way to solve this problem, but these are all the tools I have (first-year comp sci student that hasn't programmed seriously since I was 16). I'm writing a function to remove the corresponding element from each lists, and all I know is that 1) the indices correspond and 2) the user inputs the course name. How can I remove the corresponding element from each list using filterNot? I don't think I know enough about each list to use higher order functions on them.

推荐答案

这是filter的用例:

scala> List(1,2,3,4,5)
res0: List[Int] = List(1, 2, 3, 4, 5)

scala> res0.filter(_ != 2)
res1: List[Int] = List(1, 3, 4, 5)

要在转换列表的所有元素时使用map.

You want to use map when you are transforming all the elements of a list.

这篇关于我如何习惯性地“删除"邮件?从Scala中的列表中选择一个元素并缩小差距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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