Sorting list of strings based on a list of ints (Python)
本问题已经有最佳答案,请猛点这里访问。
我有两张单子
1 2 | X = ["a","b","c","d"] Y = [3, 1, 5, 2] |
并希望将列表
1 | X = ["c","a","d","b"] |
号
根据列表中各项目的降序值,在对应的位置加1〔1〕。
默认情况下,元组按第一个值排序。
因此,首先用
1 2 3 4 | >>> sorted_list = [item[1] for item in sorted(zip(Y, X), reverse=True)] >>> sorted_list ['c', 'a', 'd', 'b'] >>> |
1 2 3 4 5 6 | X = ["a","b","c","d"] Y = [3, 1, 5, 2] zipped = zip(Y,X) zipped.sort() print zipped [(1, 'b'), (2, 'd'), (3, 'a'), (5, 'c')] |
可以使用字典保存映射,然后进行排序:
1 2 3 4 5 6 7 8 9 10 | >>> X ['a', 'b', 'c', 'd'] >>> Y [3, 1, 5, 2] >>> d = dict(zip(X, Y)) >>> sorted(X, key=lambda x: d[x], reverse=True) ['c', 'a', 'd', 'b'] |
号