python实现对列表进行排序并返回排序后的索引值
时间: 2024-01-06 13:04:49 浏览: 58
可以使用 `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对列表排序,并返回索引
可以使用 `sorted` 函数和列表的 `index` 方法来实现:
```python
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_idx = sorted(range(len(lst)), key=lambda i: lst[i])
```
其中,`sorted` 函数的 `key` 参数指定了排序规则,这里使用了一个 lambda 函数,将列表中各个元素的索引作为参数,返回对应元素的值作为排序依据。
`sorted_idx` 列表中的元素就是 `lst` 中元素按照升序排列后的索引。例如,`sorted_idx` 的第一个元素就是 `lst` 中最小值的索引。
如果需要按照降序排列,可以将 lambda 函数中的 `lst[i]` 改为 `-lst[i]`。
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 参数即可
```
这样就可以得到一个排序后的列表,并且可以根据原来的索引值找到对应的元素。