通过索引在列表中进行Scala筛选 [英] Scala filter on a list by index
本文介绍了通过索引在列表中进行Scala筛选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写在功能上,我能做的最好的是:
list.zipWithIndex.filter((tt :Tuple2 [Thing,Int])=>(tt._2%3 == 0))。unzip._1
获取元素0,3,6,...
是否有更具可读性的Scala成语?
解决方案
如果效率不是问题,您可以执行以下操作:
list.grouped(3).map(_。head)
注意这个构造中间名单。
或者,您可以使用理解:
for {
(x,i)< - list zipWithIndex
if i%3 == 0
} yield x
这当然与您原来的解决方案几乎相同,只是写法不同而已。
我的最后一种替代方法是使用收集的压缩列表:
list.zipWithIndex.collect {
case(x,i)if一世%3 == 0 => x
}
I wanted to write it functionally, and the best I could do was:
list.zipWithIndex.filter((tt:Tuple2[Thing,Int])=>(tt._2%3==0)).unzip._1
to get elements 0, 3, 6,...
Is there a more readable Scala idiom for this?
解决方案
If efficiency is not an issue, you could do the following:
list.grouped(3).map(_.head)
Note that this constructs intermediate lists.
Alternatively you can use a for-comprehension:
for {
(x,i) <- list zipWithIndex
if i % 3 == 0
} yield x
This is of course almost identical to your original solution, just written differently.
My last alternative for you is the use of collect on the zipped list:
list.zipWithIndex.collect {
case (x,i) if i % 3 == 0 => x
}
这篇关于通过索引在列表中进行Scala筛选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文