你可以使用sorted()
函数来按照另一个列表的顺序对Python列表进行排序,并使用enumerate()
函数来检索旧索引。下面是一个示例代码:
# 初始化列表
my_list = ['b', 'a', 'd', 'c', 'e']
order_list = [1, 3, 0, 4, 2]
# 使用sorted()函数按照另一个列表的顺序对列表进行排序
sorted_list = sorted(my_list, key=lambda x: order_list.index(my_list.index(x)))
# 使用enumerate()函数检索旧索引
old_index_list = [i for i, _ in sorted(enumerate(my_list), key=lambda x: order_list.index(x[0]))]
# 打印结果
print(sorted_list) # ['a', 'c', 'e', 'b', 'd']
print(old_index_list) # [1, 3, 0, 4, 2]
在上面的代码中,我们首先定义了my_list
和order_list
两个列表。然后,我们使用sorted()
函数对my_list
进行排序,使用order_list.index(my_list.index(x))
作为排序的关键字,以按照order_list
的顺序对my_list
进行排序。
接下来,我们使用enumerate()
函数获取my_list
中每个元素的旧索引,并使用order_list.index(x[0])
作为排序的关键字,以按照order_list
的顺序对旧索引进行排序。
最后,我们将排序后的列表sorted_list
和排序后的旧索引列表old_index_list
打印出来。