【问题标题】:Sort a list of `List[Any]` by the first element using Scala使用 Scala 按第一个元素对 `List[Any]` 列表进行排序
【发布时间】:2018-07-16 14:45:10
【问题描述】:

我想按 scala 中的第一列对列表进行排序。

我有一个这样的列表:

val a0 = List(0, "a0", 23)
val a1 = List(1, "a1", 231)
val a2 = List(2, "a2", 1)
val a3 = List(3, "a3", 80)
val a4 = List(4, "a4", 33)
val a5 = List(5, "a5", 23)
val a6 = List(6, "a6", 2)
val list1 = List(a0, a6, a2, a3, a1, a5, a4)

我想按第一列排序,所以预期的输出是:

List(  
  List(0, a0, 23),
  List(1, a1, 231),
  List(2, a2, 1),
  List(3, a3, 80),
  List(4, a4, 33),
  List(5, a5, 23),
  List(6, a6, 2)
)

我试过了

list1.sortBy(list => list(0))

但它会产生

错误:没有为 Any 定义隐式排序

我该怎么做?

【问题讨论】:

  • 请提供输出格式
  • 对不起,我已经穿上了。
  • 生成输入码:for ((k,j) <- List(23, 231, 1, 80, 33, 23, 2).zipWithIndex) println(s"""val a$j = List($j, "a$j", $k)"""); println(List(0,6,2,3,1,5,4).map("a" + _).mkString("val list1 = List(", ", ", ")"));请不要将代码作为图片发布。
  • 对不起,我是新来的。我想用 list1 来产生结果,你能用 sorted、sortBy 或 sortWith 得到结果吗?谢谢。

标签: scala sorting casting


【解决方案1】:

这又是您的输入:

val a0 = List(0, "a0", 23)
val a1 = List(1, "a1", 231)
val a2 = List(2, "a2", 1)
val a3 = List(3, "a3", 80)
val a4 = List(4, "a4", 33)
val a5 = List(5, "a5", 23)
val a6 = List(6, "a6", 2)
val list1 = List(a0, a6, a2, a3, a1, a5, a4)

这是你的排序方式:

val list2 = list1.sortBy(_(0).asInstanceOf[Int])

(0) 获取第一个条目,asInstanceOf[Int] 将其转换为整数。 _ 是列表的占位符,是(list: List[Any]) => list(0).asInstanceOf[Int] 的缩写。

如果打印结果

list2 foreach println

你得到

List(0, a0, 23)
List(1, a1, 231)
List(2, a2, 1)
List(3, a3, 80)
List(4, a4, 33)
List(5, a5, 23)
List(6, a6, 2)

【讨论】:

  • 不错的@Andrey。
  • @ChaitanyaWaikar 生成输入比问题本身更“有趣”,但我认为_asInstanceOf-parts 对于普通 python 用户来说都不是特别明显,因为示例...
  • 你完美解决了我的问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2020-08-02
相关资源
最近更新 更多