Sorts one list based on another list containing the desired indexes.

Use zip() and sorted() to combine and sort the two lists, based on the values of indexes. Use a list comprehension to get the first element of each pair from the result.

Code:

def sort_by_indexes(lst, indexes):
return [val for _, val in sorted(zip(indexes, lst), key = lambda x: x[0])]

EXAMPLES

a = [‘eggs’, ‘bread’, ‘oranges’, ‘jam’, ‘apples’, ‘milk’]
b = [3, 2, 6, 4, 1, 5]
sort_by_indexes(a, b) # [‘apples’, ‘bread’, ‘eggs’, ‘jam’, ‘milk’, ‘oranges’]

Share and Support t.me/python_codes

原文链接:Sorts one list based on another list containing the desired indexes.

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容