我有一个列表:
test1 = ["a","b","c","d","e","f","g","h","i"]
和一个元组列表:
test2 = [("c",1),("g",1),("b",1),("e",1),("g",1),("d",10),("a",10)]
我需要排序:
[val for (key, val) in test2]
并且当 val 与 test1 排序的相同 val 相等时:
test3 = [("b",1),("c",1),("e",1),("f",1),("g",1),("a",10),("d",10)]
请您参考如下方法:
sorted接受可选参数 key。使用函数的返回值(每个项目都传递给函数)而不是项目本身。
>>> test1 = ["a","b","c","d","e","f","g","h","i"]
>>> test2 = [("c",1),("g",1),("b",1),("e",1),("g",1),("d",10),("a",10)]
>>> sorted(test2, key=lambda x: (x[1], test1.index(x[0])))
[('b', 1), ('c', 1), ('e', 1), ('g', 1), ('g', 1), ('a', 10), ('d', 10)]
鉴于上述关键函数顺序将首先按数字,然后在 test1 中定位。
