python去重排序
时间: 2023-11-08 09:02:08 浏览: 63
你可以使用Python中的set()函数来进行去重操作,然后使用sorted()函数对其进行排序。
以下是一个示例代码:
```python
lst = [1, 3, 2, 4, 2, 5, 1]
unique_sorted_lst = sorted(set(lst))
print(unique_sorted_lst)
```
输出结果为:[1, 2, 3, 4, 5]
相关问题
python列表去重排序
如果你想在Python中对列表进行选择性的去重和排序,可以使用列表推导式和内置函数来实现。下面是一个示例代码:
```python
my_list = [3, 1, 2, 3, 4, 1, 2]
sorted_list = sorted(list(set([x for x in my_list if my_list.count(x) == 1])))
print(sorted_list)
```
这里的列表推导式`[x for x in my_list if my_list.count(x) == 1]`会遍历原始列表`my_list`中的每个元素,并仅保留出现次数为1的元素。然后,我们将得到的列表转换为集合(set),再使用`sorted()`函数对集合进行排序,最后将排序后的集合转换回列表。
输出结果为:
python字符串去重排序
以下是Python的字符串去重排序代码示例:
```
string = "Hello World!"
unique_chars = sorted(set(string))
print("".join(unique_chars))
```
输出结果为:` !HdWelo`
解释:代码中使用了Python的set()函数去除字符串中的重复字符,然后使用sorted()函数对去重后的字符列表进行排序。最后使用join()函数将字符列表转换为字符串输出。