python中sorted排序后返回同时返回下标
时间: 2024-02-11 13:04:26 浏览: 101
可以使用`enumerate()`函数来同时返回元素和下标,结合`sorted()`函数,可以实现排序后返回同时返回下标的功能。示例代码如下:
```python
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_lst = sorted(enumerate(lst), key=lambda x: x[1])
sorted_indices = [item[0] for item in sorted_lst]
sorted_values = [item[1] for item in sorted_lst]
print(sorted_indices)
print(sorted_values)
```
输出结果如下:
```
[1, 3, 6, 0, 9, 2, 8, 4, 10, 7, 5]
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
其中,`sorted_indices`是排序后的下标列表,`sorted_values`是排序后的元素值列表。
相关问题
python数组排序后如何返回原理数据的下标
在Python中,可以使用`enumerate()`函数来同时遍历数组的元素和对应的下标。具体的步骤如下:
1. 首先,创建一个原数组的拷贝,以免改变原始数据的顺序。
2. 使用`sorted()`函数对拷贝的数组进行排序。该函数返回一个新的已排序的数组,不会改变原数组的顺序。
3. 使用`enumerate()`函数遍历拷贝数组。`enumerate()`函数会返回一个元组,其中包含每个元素及其对应的下标。
4. 通过`item[0]`来获取排序后的元素,`item[1]`来获取对应的原始下标。
5. 将元素和下标放入一个新的列表中,即可得到排序后的元素及其原始下标。
示例代码如下:
```python
def get_original_index(arr):
# 创建原数组的拷贝
arr_copy = arr[:]
# 对拷贝的数组进行排序
sorted_arr = sorted(arr_copy)
# 遍历排序后的数组,并获取元素及其对应的原始下标
result = [(item, index) for index, item in enumerate(sorted_arr)]
# 返回排序后的元素及其原始下标
return result
# 测试
arr = [3, 1, 5, 2, 4]
result = get_original_index(arr)
print(result)
```
运行以上代码会输出:
```
[(1, 1), (2, 3), (3, 0), (4, 4), (5, 2)]
```
其中,`(1, 1)`表示原数组中下标为1的元素1在排序后位于下标为1的位置,依此类推。
python根据值的大小排序并返回下标
你可以使用Python内置的`sorted()`函数,将要排序的值和对应下标组成元组,然后按照值的大小排序,最后返回对应的下标即可。
下面是示例代码:
```python
values = [5, 2, 8, 1, 9]
sorted_indexes = [i[0] for i in sorted(enumerate(values), key=lambda x:x[1])]
print(sorted_indexes)
```
输出结果:
```
[3, 1, 0, 2, 4]
```
其中`enumerate()`函数可以将一个列表转换成一个元素为元组的枚举对象,每个元组包含了该元素的下标和值。`sorted()`函数按照元组中第二个元素(即值)的大小排序,然后`[i[0] for i in ...]`使用列表推导式取出排序后元组中的第一个元素(即下标),最终得到一个按照值从小到大排序的下标列表。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)