列表串联在 scala 中不起作用

List concatenation not working in scala

我正在尝试使用以下代码在循环中连接 Scala 列表。

var names: List[String] = Nil
val cluster_id = List("149095311_0", "149095311_1")
for (id <- cluster_id) {
  val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher)
  println("In Loop " + influencers_name)
  names :::= influencers_name
}
for(n <- names) println("List element -> " + n) 

但是当我遍历最终列表时,它会给我单独的列表而不是串联列表的单独元素。

下面是上面代码的O/P:

In Loop List(kroger 10TV DispatchAlerts)
In Loop List(kroger seanhannity SenTedCruz)
List element -> kroger seanhannity SenTedCruz 
List element -> kroger 10TV DispatchAlerts 

看起来问题出在 searchIndex 方法中,该方法使用单个字符串检索 List[String],其中包含由 space 分隔的所有值,请修复该方法以确保它检索到一个列出每个值一个元素。

要检查这是否正确,试试这个,这只是一种解决方法,您应该修复 searchIndex

var names: List[String] = Nil
val cluster_id = List("149095311_0", "149095311_1")
for (id <- cluster_id) {
  val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher).flatMap(_.split(' '))
  ("In Loop " + influencers_name)
  names = influencers_name ::: names
}
for(n <- names) println("List element -> " + n) 

原因是, 当您执行 names :::: List("anything") -> 它不会向名称添加任何内容。 相反,它创建了一个新的集合。 例如,

scala> var names: List[String] = Nil
names: List[String] = List()

scala> names ::: List("mahesh")
res0: List[String] = List(mahesh)

You can achive that

scala> names ::: List("chand")
res1: List[String] = List(chand)

scala> res0 ::: List("chand")
res2: List[String] = List(mahesh, chand)

当我向它添加 "Mahesh" 时,它创建了一个名为 res0 的新集合。 当我再次添加不同的字符串时,这里 "chand" 它创建了另一个集合。但是当我将 "chand" 添加到创建的集合时,它已连接到正确的集合,

你可以实现你想做的事,

scala> for(i <- List("a" ,"b" )){
     | names = i :: names } 

scala> names
res11: List[String] = List(b, a)

您的代码不是很实用,因为您正在改变变量。下面是比较优雅的:

def searchIndex(s: String): List[String] = {
  if (s == "149095311_0") List("kroger 10TV DispatchAlerts")
  else List("kroger seanhannity SenTedCruz")
}

val cluster_id = List("149095311_0", "149095311_1")

val names = cluster_id.foldLeft(List[String]()) {
  (acc, id) => acc ++ searchIndex(id)
}

for(n <- names) println("List element -> " + n)

其中“++”用于连接两个列表的元素。