[英]Sort list of tuple
I need the first abbreviations(like "VBM") from to_sort to be in the same order as in sort_list我需要 to_sort 中的第一个缩写(如“VBM”)与 sort_list 中的顺序相同
to_sort = [['SSW', 'Sergey Sirotkin', 'WILLIAMS MERCEDES'], ['SVF', 'Sebastian Vettel', 'FERRARI'], ['SVM', 'Stoffel Vandoorne', 'MCLAREN RENAULT'], ['VBM', 'Valtteri Bottas', 'MERCEDES']]
sort_list = [('VBM', '1:12.433'), ('SSW', 'Error time'), ('SVM', '1:12.463'), ('SVF', '1:44.414')]
example = [['VBM', 'Valtteri Bottas', 'MERCEDES'], ['SSW', 'Sergey Sirotkin', 'WILLIAMS MERCEDES'], ['SVM', 'Stoffel Vandoorne', 'MCLAREN RENAULT'], ['SVF', 'Sebastian Vettel', 'FERRARI']]
One solution is to create mapping where keys are abbreviations and values are positions of these keys:一种解决方案是创建映射,其中键是缩写,值是这些键的位置:
mapping = {v: idx for idx, (v, _) in enumerate(sort_list)}
out = sorted(to_sort, key=lambda x: mapping[x[0]])
print(out)
Prints:印刷:
[
["VBM", "Valtteri Bottas", "MERCEDES"],
["SSW", "Sergey Sirotkin", "WILLIAMS MERCEDES"],
["SVM", "Stoffel Vandoorne", "MCLAREN RENAULT"],
["SVF", "Sebastian Vettel", "FERRARI"],
]
Alternative (without mapping):备选方案(无映射):
out = sorted(
to_sort,
key=lambda i: next(
idx for idx, (v, _) in enumerate(sort_list) if v == i[0]
),
)
print(out)
You can generate list of first items of sort_list
and call list.index()
to get index of element (as suggested in this comment) .您可以生成
sort_list
的第一项列表并调用list.index()
以获取元素的索引(如本评论中所建议) 。
to_sort.sort(key=lambda x, l=[i for i, _ in sort_list]: l.index(x[0]))
Results of benchmark : 基准测试结果:
sort_olvin 0.2418229230097495
sort_olvin_inline 0.22788053899421357
sort_andrej_1 0.2182700579869561
sort_andrej_1_inline 0.19632228900445625
sort_andrej_2 0.5893592859792989
sort_andrej_2_inline 0.5593071450130083
First option offered by @AndrejKesely in his answer is fastest, so I recommend you to use it, but (if it's not necessary to keep original list) it's a bit faster to use inline list.sort()
. @AndrejKesely在他的回答中提供的第一个选项是最快的,所以我建议您使用它,但是(如果不需要保留原始列表)使用内联
list.sort()
会更快一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.