深度阅读

How to Sort a Set of Values in Python?

作者
作者
2023年08月22日
更新时间
6.83 分钟
阅读时间
0
阅读量

Sets in Python are unordered, and therefore don’t have a sort method like lists do. However, you can convert the set into a list and then sort it using the built-in sorted() function.

Here’s an example:

my_set = {4, 2, 1, 5, 3}
sorted_set = sorted(my_set)
print(sorted_set)

This will output:

[1, 2, 3, 4, 5]

Note that the sorted() function returns a new sorted list and does not modify the original set. If you need to convert the sorted list back into a set, you can use the set() function:

my_set = {4, 2, 1, 5, 3}
sorted_list = sorted(my_set)
sorted_set = set(sorted_list)
print(sorted_set)

This will output:

{1, 2, 3, 4, 5}

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。