【问题标题】:Sort list of string based on length根据长度对字符串列表进行排序
【发布时间】:2018-02-23 00:16:15
【问题描述】:

我有一个字符串列表

List("cbda","xyz","jlki","badce")

我想对字符串进行排序,奇数长度的字符串按降序排序,偶数长度的字符串按升序排序

List("abcd","zyx","ijkl","edcba")

现在我通过分别迭代每个元素,然后找到它们的长度并相应地对它们进行排序来实现这一点。最后,我将它们存储在单独的列表中。我希望知道在 Scala 中是否有任何其他有效的方法可以做到这一点,或者有任何更短的方法来做到这一点(比如我们在 Python 中的某种列表推导)?

【问题讨论】:

  • 您可以在此处添加您的排序代码以供参考吗?
  • @Shaido 我在搜索for(e<-lst) yield if (e.length%2==0) e.sortWith(_ < _) else e.sortWith(_ > _)后找到了解决方案

标签: string scala list sorting


【解决方案1】:

你可以用 sortWith 和 map 做到这一点:

list.map(s => {if(s.length % 2 == 0) s.sortWith(_ < _) else s.sortWith(_ > _)})

【讨论】:

  • 谢谢!虽然我是这样使用for 做到的:for(e&lt;-lst) yield if (e.length%2==0) e.sortWith(_ &lt; _) else e.sortWith(_ &gt; _)
  • 你不需要说两次sortWithe.sortWith(if (e.length % 2 == 0) (_ &lt; _) else (_ &gt; _)))
【解决方案2】:

我不确定你在 Python 中指的是什么,所以如果下面的示例不符合你的期望,那么详细信息可能会有所帮助

第一个,让你遍历列表两次:

List("cbda","xyz","jlki","badce").map(_.sorted).map {
  case even if even.length % 2 == 0 => even
  case odd => odd.reverse
}

或者让你遍历偶数长度的元素两次:

List("cbda","xyz","jlki","badce").map {
  case even if even.length % 2 == 0 => even.sorted
  case odd => odd.sorted.reverse
}

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 2013-11-05
    • 1970-01-01
    • 2020-01-23
    • 2020-06-28
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多