如何从排序列表中选择第二小的元素? [英] How to select the second smallest element from sorted list?

查看:48
本文介绍了如何从排序列表中选择第二小的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在列表排序后选择第二小的元素?

How can I select the second smallest element after that a list has been sorted?

使用此代码时出现错误,我不明白为什么.

With this code I get an error and I do not understand why.

object find_the_median {
  val L = List(2,4,1,2,5,6,7,2)

  L(2)
  L.sorted(2) // FIXME returns an error
}

推荐答案

这是因为 sorted 隐含地接收了一个 Ordering 参数,当你像 L 一样这样做时.sorted(2) 类型检查器认为您希望将 2 作为 Ordering 传递.因此,在一行中完成的一种方法是:

It's because sorted receives implicitly an Ordering argument, and when you do it like L.sorted(2) the typechecker thinks you want to pass 2 as an Ordering. So one way to do it in one line is:

L.sorted.apply(2)

或者为了避免 apply 明确传递排序:

or to avoid the apply pass the ordering explicitly:

L.sorted(implicitly[Ordering[Int]])(2)

我承认这有点令人困惑,所以我认为最好的是两行:

which I admit is somewhat confussing so I think the best one is in two lines:

val sorted = L.sorted
sorted(2)

(您可能还想遵守 Scala 用小写命名变量的约定).

(You may also want to adhere to the Scala convention of naming variables with lowercase).

这篇关于如何从排序列表中选择第二小的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆