内置函数sorted()
返回给定 iterable 的排序列表。排序可以是升序或降序。如果 iterable 是字符串,则按字母顺序排序;如果是数字,则按数字排序。对于既有字符串又有不能排序的数字的可重复项。
专注于为中小企业提供网站建设、网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业射阳免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
**sorted(iterable, key=None, reverse=False)** #where iterable may be string, tuple, list,set, dictionary frozen set)
取三个参数。根据 key 函数的返回值,我们可以对给定的 iterable 进行如下排序
已排序(可迭代,key=len)
参数 | 描述 | 必需/可选 |
---|---|---|
可迭代的 | 序列(字符串、元组、列表)或集合(集合、字典、冻结集合)或任何其他迭代器。 | 需要 |
反面的 | 如果为真,则排序列表反转(或按降序排序)。如果未提供,则默认为假。 | 可选择的 |
键 | 用作排序比较的关键字的函数。默认为无。 | 可选择的 |
这个sorted()
方法类似于sorted()
,不同的是sorted()
不返回值。
| 投入 | 返回值 | | 可重复的 | 排序列表 |
sorted()
方法示例 # vowels list pyth 'a', 'u', 'o', 'i']
print(sorted(python_list))
# string pyth
print(sorted(python_string))
# vowels tuple pyth 'a', 'u', 'o', 'i')
print(sorted(python_tuple))
输出:
['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']
# set pyth 'a', 'u', 'o', 'i'}
print(sorted(python_set, reverse=True))
# dictionary pyth 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(python_dict, reverse=True))
# frozen set
frozen_set = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(frozen_set, reverse=True))
输出:
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
sorted()
对列表进行排序 # take the second element for sort
def take_second(elem):
return elem[1]
# random list
randomnum = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
sorted_keylist = sorted(randomnum, key=take_second)
# print list
print('Sorted list:', sorted_keylist)
输出:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]
# Nested list of student's info in a Science Olympiad
# List elements: (Student's Name, Marks out of 100, Age)
student_list = [
('Alison', 50, 18),
('Terence', 75, 12),
('David', 75, 20),
('Jimmy', 90, 22),
('John', 45, 12)
]
输出:
[('Jimmy', 90, 22), ('Terence', 75, 12), ('David', 75, 20), ('Alison', 50, 18), ('John', 45, 12)]
文章标题:创新互联Python教程:Pythonsorted()
分享网址:http://www.shufengxianlan.com/qtweb/news37/142487.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联