python sorted三个例子

简介: # 例1. 按照元素出现的次数来排序seq = [2,4,3,1,2,2,3]# 按次数排序seq2 = sorted(seq, key=lambda x:seq.count(x))print(seq2) # [4, 1, 3, 3, 2, 2, 2]# 改进:第一优先按次数,第二优先按值seq3 = sorted(seq, key=lambda x:(seq.count(x), x))print(seq3) # [1, 4, 3, 3, 2, 2, 2]'''原理: 先比较元组的第一个值,值小的在前。
# 例1. 按照元素出现的次数来排序
seq = [2,4,3,1,2,2,3]

# 按次数排序
seq2 = sorted(seq, key=lambda x:seq.count(x))
print(seq2) # [4, 1, 3, 3, 2, 2, 2]

# 改进:第一优先按次数,第二优先按值
seq3 = sorted(seq, key=lambda x:(seq.count(x), x))
print(seq3) # [1, 4, 3, 3, 2, 2, 2]

'''
原理:
    先比较元组的第一个值,值小的在前。(注意:False < True)
    如果相等就比较元组的下一个值,以此类推。
'''
#例2.这是一个字符串排序,排序规则:小写<大写<奇数<偶数
s = 'asdf234GDSdsf23'

s2 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)))
print(s2) # addffssDGS33224
#例3. 一道面试题:
list1 = [7, -8, 5, 4, 0, -2, -5]
#要求1.正数在前负数在后 2.正数从小到大 3.负数从大到小

list2 = sorted(list1,key=lambda x:(x<0, abs(x)))
print(list2) # [0,4,5,7,-2,-5,-8]
目录
相关文章
|
5月前
|
Python
python sort和sorted的区别
在Python中,sort()和sorted()都是用于排序的函数,但它们之间存在一些关键的区别,这些区别主要体现在它们的应用方式、操作对象以及对原始数据的影响上。
|
5天前
|
Python
Python sorted() 函数和sort()函数对比分析
Python sorted() 函数和sort()函数对比分析
|
5月前
|
算法 程序员 Python
python排序的几种方法(1)
python排序的几种方法(1)
|
5月前
|
算法 开发工具 Python
python排序的几种方法(3)
python排序的几种方法(3)
|
5月前
|
搜索推荐 Python
写个python排序代码
写个python排序代码
65 7
|
5月前
|
Python
Python系列(22)—— 排序函数
Python系列(22)—— 排序函数
|
Python
Python内置函数--sorted()
Python内置函数--sorted()
64 0
|
5月前
|
Python
Python中sorted函数使用,一看就会
Python中sorted函数使用,一看就会
47 0
|
5月前
python-sorted()函数
python-sorted()函数
35 0
|
Python
python sorted()函数及sort()方法
python sorted()函数及sort()方法
158 0
python sorted()函数及sort()方法
下一篇
无影云桌面