gpt4 book ai didi

Scala 按索引过滤列表

转载 作者:行者123 更新时间:2023-12-01 18:11:32 26 4
gpt4 key购买 nike

我想用函数式的方式来编写它,我能做的最好的事情是:

list.zipWithIndex.filter((tt:Tuple2[Thing,Int])=>(tt._2%3==0)).unzip._1

获取元素 0, 3, 6,...

是否有更易读的 Scala 习惯用法?

最佳答案

如果效率不是问题,您可以执行以下操作:

list.grouped(3).map(_.head)

请注意,这会构造中间列表。

或者,您可以使用 for 理解:

for {
(x,i) <- list zipWithIndex
if i % 3 == 0
} yield x

这当然与您原来的解决方案几乎相同,只是写法不同。

我为您提供的最后一个选择是在压缩列表上使用收集:

list.zipWithIndex.collect {
case (x,i) if i % 3 == 0 => x
}

关于Scala 按索引过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com