Home > Blockchain >  Sort list of tuple
Sort list of tuple

Time:10-14

I need the first abbreviations(like "VBM") from to_sort to be in the same order as in 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']]

CodePudding user response:

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)

CodePudding user response:

You can generate list of first items of sort_list and call list.index() to get index of element (as suggested in this comment).

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().


You can help my country, check my profile info.

  • Related