Vat*_*tec 3 python sorting string
我正在寻找一种按另一个字符串中出现的顺序对列表进行排序的方法,以便以下代码
thelist = ["a", "b", "c"]
thestring = "b c a"
Run Code Online (Sandbox Code Playgroud)
将能够被分类为
["b", "c", "a"]
Run Code Online (Sandbox Code Playgroud)
因为这是每个列表对象在字符串中出现的顺序。
我将如何实现这一目标?是否可以使用带有某些参数的排序函数来轻松实现此目的或其他目的?谢谢。
将字符串转换为地图:
indices = {c: i for i, c in enumerate(thestring.split())}
Run Code Online (Sandbox Code Playgroud)
然后使用该地图进行排序:
sorted(thelist, key=indices.get)
Run Code Online (Sandbox Code Playgroud)
这允许值thestring 缺失,thelist反之亦然。这也适用于 中的重复元素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']
Run Code Online (Sandbox Code Playgroud)