在Seq中获取实例的最佳做法是什么?
case class Point(x: Int, y: Int)
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
我想以最大y获得Point。 (在这种情况下:Point(3, 30)
)
最好的方法是什么?
答案 0 :(得分:4)
最简单的方法是使用TraversableOnce.maxBy
:
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
scala> points.maxBy(_.y)
res1: Point = Point(3,30)
答案 1 :(得分:4)
@YuvalItzchakov的答案是正确的,但在这里使用Ordering进行另一种方式:
val points: Seq[Point] = Seq(Point(1, 10), Point(2, 20), Point(3, 30))
// points: Seq[Point] = List(Point(1,10), Point(2,20), Point(3,30))
val order = Ordering.by((_: Point).y)
// order: scala.math.Ordering[Point] = scala.math.Ordering$$anon$9@5a2fa51f
val max_point = points.reduce(order.max)
// max_point: Point = Point(3,30)
或
points.max(order)
// Point = Point(3,30)
或implicit
Ordering
:
{
implicit val pointOrdering = Ordering.by((_: Point).y)
points.max
}
// Point = Point(3,30)
注意:TraversableOnce.maxBy
也使用隐式排序。 Reference
答案 2 :(得分:0)
另一种方法是使用foldleft。
def main():
_list_ = []
for i in range(2, 10001):
_list_.append(i)
k=0
while k<10000-2:# n starts from 2
n = _list_[k]
multiple = 2*n
while multiple <= 10000:
multiple += n
_list_.remove(multiple)
k = k + 1
main()