循环遍历 Scala 中的元组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36393883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through a list of tuples in Scala
提问by shreekanth k.s
I have a sample Listas below
我有一个样本List如下
List[(String, Object)]
How can I loop through this list using for?
如何使用 循环遍历此列表for?
I want to do something like
我想做类似的事情
for(str <- strlist)
but for the 2d list above. What would be placeholder for str?
但对于上面的二维列表。什么是占位符str?
采纳答案by xrs
I will suggest using map, filter,fold or foreach(whatever suits your need) rather than iterating over a collection using loop.
我建议使用 map、filter、fold 或 foreach(任何适合您的需要),而不是使用循环遍历集合。
Edit 1: e.g if you want to apply some func foo(tuple) on each element
编辑 1:例如,如果您想在每个元素上应用一些 func foo(tuple)
val newList=oldList.map(tuple=>foo(tuple))
val tupleStrings=tupleList.map(tuple=>tuple._1) //in your situation
if you want to filter according to some boolean condition
如果你想根据一些布尔条件进行过滤
val newList=oldList.filter(tuple=>someCondition(tuple))
or simply if you want to print your List
或者只是如果你想打印你的列表
oldList.foreach(tuple=>println(tuple)) //assuming tuple is printable
you can find example and similar functions here
https://twitter.github.io/scala_school/collections.html
你可以在这里找到示例和类似的功能
https://twitter.github.io/scala_school/collections.html
回答by u5827450
Here it is,
这里是,
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
Note: The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, { case (id, name) => ... }
注意:预期的类型需要一个接受 2 元组的单参数函数。考虑一个模式匹配匿名函数,{ case (id, name) => ... }
Easy to copy code:
易于复制的代码:
val fruits: List[(Int, String)] = List((1, "apple"), (2, "orange"))
fruits.foreach {
case (id, name) => {
println(s"$id is $name")
}
}
回答by echo
With foryou can extract the elements of the tuple,
随着for您可以提取元组的元素,
for ( (s,o) <- list ) yield f(s,o)
回答by Tyler
If you just want to get the strings you could map over your list of tuples like this:
如果您只想获取字符串,您可以像这样映射元组列表:
// 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)
Note: Tuple members are accessed using the underscore notation (which is indexed from 1, not 0)
注意:元组成员使用下划线表示法访问(从 1 索引,而不是 0)

