可以使用Python中的sorted函数来实现。首先将原始列表转换成列表包含索引和值的元组列表,然后使用sorted函数按值和位置排序元组列表。最后将排好序的元组列表中的索引提取出来并返回。
示例代码如下:
def sort_by_value_then_index(my_list): # 转换成包含索引和值的元组列表 indexed_list = [(index, value) for index, value in enumerate(my_list)] # 按照值和位置排序元组列表 sorted_list = sorted(indexed_list, key=lambda x: (x[1], x[0])) # 提取排序后的元组列表中的索引 sorted_indices = [x[0] for x in sorted_list] return sorted_indices
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_indices = sort_by_value_then_index(my_list) print(sorted_indices)
上一篇:按值进行分组,但仅适用于连续值。