Python: 按另一个字符串的顺序排序字符串列表
我想找到一种方法,把一个列表按照另一个字符串中的出现顺序进行排序。这样,下面的代码
thelist = ["a", "b", "c"]
thestring = "b c a"
就能被排序成
["b", "c", "a"]
因为这是列表中的每个对象在字符串中出现的顺序。
我该怎么做呢?可以用 sorted 函数加上一些参数来轻松实现这个吗,还是需要其他方法?谢谢。
1 个回答
6
把你的字符串变成一个映射:
indices = {c: i for i, c in enumerate(thestring.split())}
然后用这个映射进行排序:
sorted(thelist, key=indices.get)
这样可以处理在 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']