【问题标题】:Python: sort list of strings in order that they appear in another stringPython:对字符串列表进行排序,以便它们出现在另一个字符串中
【发布时间】:2014-08-17 10:07:49
【问题描述】:

我正在寻找一种方法来按在另一个字符串中出现的顺序对列表进行排序,以便以下代码

thelist = ["a", "b", "c"]
thestring = "b c a"

就能被排序成

["b", "c", "a"]

因为这是每个列表对象在字符串中出现的顺序。

我将如何实现这一目标?是否可以使用带有特定参数的 sorted 函数来轻松实现此目的或其他目的? 谢谢。

【问题讨论】:

  • 只使用thestring.split()而不是排序thelist?
  • 你可以试试.sort(key=lambda c: thestring.index(c)),但这不能很好地处理重复
  • 是的,我需要能够在有多个的地方进行排序,还有其他方式吗?
  • @Vatec 这是重复字符时的非确定性排序! (或者换句话说 - 你不能......)
  • @Vatec:多个什么thelist 中的重复元素?还是在thestring 中重复?在哪种情况下

标签: python string sorting


【解决方案1】:

把你的字符串变成地图:

indices = {c: i for i, c in enumerate(thestring.split())}

然后使用该地图进行排序:

sorted(thelist, key=indices.get)

这允许 thelist 中来自 thestring missing 的值,反之亦然。这也适用于 thelist 中的重复元素。

演示:

>>> thestring = "b c a"
>>> indices = {c: i for i, c in enumerate(thestring.split())}
>>> sorted(['a', 'b', 'c'], key=indices.get)
['b', 'c', 'a']
>>> sorted(['a', 'b', 'c', 'a', 'c', 'b'], key=indices.get)
['b', 'b', 'c', 'c', 'a', 'a']
>>> sorted(['a', 'a', 'a'], key=indices.get)
['a', 'a', 'a']
>>> sorted(['a', 'e', 'b'], key=indices.get)
['e', 'b', 'a']

【讨论】:

  • 谢谢,除了字符串不总是用空格分隔之外,这会起作用,它可能是需要产生 ["c", b"] 的 "ycyby"
  • @Vatec:然后使用{c: i for i, c in enumerate(thestring)},确切的整数值并不重要。
  • @Vatec:也许以后你可以对这些要求更清楚一点?
  • 谢谢,对不起,我是python和stackoverflow的新手,下次我会更清楚
  • 完美答案!! (Windows 服务器 2012 R2;Python 3.7)
猜你喜欢
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 2020-01-31
  • 2013-01-02
  • 2021-03-27
  • 2012-11-26
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多