我是Scala的新手。 我有一个元组[Int,String]
((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
对于上面的列表,我想打印相应长度为4的所有字符串。
答案 0 :(得分:1)
在Scala中打印Tuples字符串的长度
val tuples = List((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
println(tuples.map(x => (x._2, x._2.length)))
//List((alpha,5), (beta,4), (gamma,5), (zeta,4), (omega,5))
我想打印相应长度为4的所有字符串
您可以filter
先行,然后print
作为
val tuples = List((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
tuples.filter(_._2.length == 4).foreach(x => println(x._2))
它应该打印
beta
zeta
答案 1 :(得分:1)
您可以将Tuple
转换为List
,然后根据需要进行映射和过滤:
tuple.productIterator.toList
.map{case (a,b) => b.toString}
.filter(_.length==4)
示例:
对于给定的输入:
val tuple = ((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
tuple: ((Int, String), (Int, String), (Int, String), (Int, String), (Int, String)) = ((1,alpha),(2,beta),(3,gamma),(4,zeta),(5,omega))
输出:
List[String] = List(beta, zeta)
答案 2 :(得分:0)
假设你有一个元组列表,你需要所有字符串长度等于4的值。
您可以在列表中执行过滤:
val filteredList = list.filter(_._2.length == 4)
然后迭代每个元素以打印它们:
filteredList.foreach(tuple => println(tuple._2))
答案 3 :(得分:0)
以下是实现此目的的方法
scala> val x = ((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
x: ((Int, String), (Int, String), (Int, String), (Int, String), (Int, String)) = ((1,alpha),(2,beta),(3,gamma),(4,zeta),(5,omega))
scala> val y = x.productIterator.toList.collect{
case ele : (Int, String) if ele._2.length == 4 => ele._2
}
y: List[String] = List(beta, zeta)