循环遍历Scala中的元组列表

问题描述 投票:3回答:4

我有一个样本List如下

List[(String, Object)]

如何使用for遍历此列表?

我想做点什么

for(str <- strlist)

但对于上面的2d列表。什么是str的占位符?

scala
4个回答
1
投票

我建议使用map,filter,fold或foreach(适合你的需要),而不是使用循环遍历集合。

编辑1:例如,如果你想在每个元素上应用一些func foo(元组)

val newList=oldList.map(tuple=>foo(tuple))
val tupleStrings=tupleList.map(tuple=>tuple._1) //in your situation

如果你想根据一些布尔条件过滤

val newList=oldList.filter(tuple=>someCondition(tuple))

或者只是想打印你的清单

oldList.foreach(tuple=>println(tuple)) //assuming tuple is printable

你可以在这里找到示例和类似的功能 https://twitter.github.io/scala_school/collections.html


5
投票

这里是,

scala> val fruits: List[(Int, String)] = List((1, "apple"), (2, "orange"))
fruits: List[(Int, String)] = List((1,apple), (2,orange))

scala>

scala> fruits.foreach {
     |   case (id, name) => {
     |     println(s"$id is $name")
     |   }
     | }

1 is apple
2 is orange

注意:期望的类型需要单参数函数接受2元组。考虑匹配匿名函数{ case (id, name) => ... }的模式

易于复制的代码:

val fruits: List[(Int, String)] = List((1, "apple"), (2, "orange"))

fruits.foreach {
  case (id, name) => {
    println(s"$id is $name")
  }
}

2
投票

使用for,您可以提取元组的元素,

for ( (s,o) <- list ) yield f(s,o)

1
投票

如果你只想获得字符串,你可以映射到你的元组列表,如下所示:

// Just some example object
case class MyObj(i: Int = 0)

// Create a list of tuples like you have
val tuples = Seq(("a", new MyObj), ("b", new MyObj), ("c", new MyObj))

// Get the strings from the tuples
val strings = tuples.map(_._1)   

// Output: Seq[String] = List(a, b, c)

注意:使用下划线表示法(从1开始索引,而不是0)访问元组成员

© www.soinside.com 2019 - 2024. All rights reserved.