将列表排序并返回排序前的索引值的函数是哪个
时间: 2024-05-03 14:19:03 浏览: 7
Python 中可以通过 `sorted()` 函数对列表进行排序,而返回排序前的索引值可以使用 `enumerate()` 函数。下面是一个示例代码:
```python
def sort_and_return_index(lst):
sorted_lst = sorted(lst)
index_lst = [i for i, _ in enumerate(lst)]
sorted_index_lst = [index_lst[i] for i in sorted(range(len(lst)), key=lambda k: lst[k])]
return sorted_index_lst
```
该函数接受一个列表作为参数 `lst`,先使用 `sorted()` 函数对列表进行排序得到 `sorted_lst`,然后使用 `enumerate()` 函数得到索引值列表 `index_lst`。接着使用 Python 的内置函数 `sorted()` 对 `range(len(lst))` 进行排序,排序的关键字是 `lst[k]`,这里使用了 lambda 表达式来指定关键字。最后根据排序后的索引值列表 `sorted_index_lst` 返回结果。
相关问题
python实现对列表进行排序并返回排序后的索引值
可以使用 `sorted()` 函数结合 `enumerate()` 函数实现对列表进行排序并返回排序后的索引值。具体实现如下:
```python
lst = [4, 2, 3, 1]
sorted_index = [i for i, _ in sorted(enumerate(lst), key=lambda x: x[1])]
```
其中,`enumerate()` 函数可以同时返回列表的索引值和对应的元素值,然后通过 `sorted()` 函数指定按照元素值排序,得到排序后的元素值和对应的索引值。最后通过列表推导式将得到的排序后的索引值存储到 `sorted_index` 列表中。
python返回列表排序升降序形式对应原来的索引值
可以使用 `enumerate()` 函数来同时获取列表元素和索引值,然后根据元素排序并返回排序后的索引值,最后使用排序后的索引值重新构建排序后的列表。以下是示例代码:
```
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# 获取元素和索引值,构建元组列表
my_tuple_list = [(val, idx) for idx, val in enumerate(my_list)]
# 按元素排序
sorted_tuple_list = sorted(my_tuple_list)
# 获取排序后的索引值
sorted_index_list = [t[1] for t in sorted_tuple_list]
# 使用排序后的索引值重新构建排序后的列表
sorted_list = [my_list[idx] for idx in sorted_index_list]
print(sorted_list)
# 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# 对于降序排序,只需在 sorted() 函数中添加 reverse=True 参数即可
```
这样就可以得到一个排序后的列表,并且可以根据原来的索引值找到对应的元素。