按值对元组排序,当值相等时使用列表

Sorted a tuple by value use a List when the value is equal

我有一个列表:

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 相等时 valtest1 排序:

test3 = [("b",1),("c",1),("e",1),("f",1),("g",1),("a",10),("d",10)]

sorted 接受可选参数 key。使用函数的 return 值(每个项目都传递给函数)而不是项目本身。

>>> 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 中的位置。

使用 dict 将 test1 中的每个字符串映射到它的索引,因此对于按索引排序的关系,查找是 0(1):

test1 = ["a","b","c","d","e","f","g","h","i"]
inds = dict(zip(test1, range(len(test1))))

test2 = [("c",1),("g",1),("b",1),("e",1),("g",1),("d",10),("a",10)]


print(sorted(test2,key=lambda x: (x[1], inds[x[0]])))

输出:

[('b', 1), ('c', 1), ('e', 1), ('g', 1), ('g', 1), ('a', 10), ('d', 10)]

如果您真的希望字符串按排序顺序排列,您可以只使用字符串本身,使用 itemgetter 而不是 lambda:

test2 = [("c", 1), ("g", 1), ("b", 1), ("e", 1), ("g", 1), ("d", 10), ("a", 10)]
from operator import itemgetter

print(sorted(test2, key=itemgetter(1, 0)))
[('b', 1), ('c', 1), ('e', 1), ('g', 1), ('g', 1), ('a', 10), ('d', 10)]