Python sorted对list和dict排序

sorted语法

sorted(iterable, key=None, reverse=False)

参数说明:

- iterable -- 可迭代对象。
 - key --主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
 - reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

返回:
 - 一个新list对象

sorted对字典dict排序

①按键key排序

from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}

# 按key升序  .items()取得3个(key,value)
# lambda x: x[0]取(key,value)的key  即(3,1,2)
d1 = sorted(dict.items(), key=lambda x: x[0], reverse=False) # <class 'list'>

# 按key降序  itemgetter类似lambda
d2 = sorted(dict.items(), key=itemgetter(0), reverse=True) # <class 'list'>

# 输出
print(d1, type(d1)) # [(1, 'A'), (2, 'C'), (3, 'B')] <class 'list'>
print(d2, type(d2)) # [(3, 'B'), (2, 'C'), (1, 'A')] <class 'list'>

[(1, ‘A'), (2, ‘C'), (3, ‘B')] <class ‘list'>
[(3, ‘B'), (2, ‘C'), (1, ‘A')] <class ‘list'>

②按值value排序

from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}

# 按value升序  .items()取得3个(key,value)
# lambda x: x[1]取(key,value)的value  即('B','A','C')
d3 = sorted(dict.items(), key=lambda x: x[1], reverse=False) # <class 'list'>

# 按value降序  itemgetter类似lambda
d4 = sorted(dict.items(), key=itemgetter(1), reverse=True) # <class 'list'>

print(d3, type(d3)) # [(1, 'A'), (3, 'B'), (2, 'C')] <class 'list'>
print(d4, type(d4)) # [(2, 'C'), (3, 'B'), (1, 'A')] <class 'list'>

[(1, ‘A'), (3, ‘B'), (2, ‘C')] <class ‘list'>
[(2, ‘C'), (3, ‘B'), (1, ‘A')] <class ‘list'>

sorted排序list

①按一种规则排序list

from operator import itemgetter
data = [('c', 3, 'Apple'), ('d', 1, 'Cat'), ('a', 2, 'Banana')]
# 根据字母升序
print(sorted(data, key=lambda x: x[0], reverse=False)) # <class 'list'>
# 根据数字升序
print(sorted(data, key=lambda x: x[1], reverse=False)) # <class 'list'>
# 根据单词升序
print(sorted(data, key=lambda x: x[2], reverse=False)) # <class 'list'>

[('a', 2, 'Banana'), ('c', 3, 'Apple'), ('d', 1, 'Cat')]
[('d', 1, 'Cat'), ('a', 2, 'Banana'), ('c', 3, 'Apple')]
[('c', 3, 'Apple'), ('a', 2, 'Banana'), ('d', 1, 'Cat')]

②按多种规则排序list

# 先按照成绩降序排序,相同成绩的按照名字升序排序:
d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print(l)

[{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]

sorted排序list和dict的混合

先看看我们排序的有哪些类型的数据结构

#### 二维list排序
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]

#### list中混合字典
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]

#### 字典中混合list
d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}

#### 对字典中的多维list进行排序
d2 = {
  'Apple': [['44', 88], ['11', 33], ['22', 88]],
  'Banana': [['55', 43], ['11', 68], ['44', 22]],
  'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}

二维list排序

from operator import itemgetter
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]
# 按先按成绩号升序,再按成绩数值升序
print(sorted(l1, key=itemgetter(2, 1), reverse=False))
# 按先按成绩号升序,再按成绩数值降序序
print(sorted(l1, key=lambda x:(x[2], -x[1]), reverse=False))

[[‘Mandy', 82.5, ‘A'], [‘Bob', 95.0, ‘A'], [‘Alan', 86.0, ‘C'], [‘Rob', 86, ‘E']]
[[‘Bob', 95.0, ‘A'], [‘Mandy', 82.5, ‘A'], [‘Alan', 86.0, ‘C'], [‘Rob', 86, ‘E']]

2. list中混合字典

from operator import itemgetter
# 先按照成绩降序排序,相同成绩的按照名字升序排序:
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
print(sorted(l2, key=lambda x:(-x['score'], x['name'])))
print(sorted(l2, key=itemgetter('score', 'name')))

[{‘name': ‘alice', ‘score': 38}, {‘name': ‘christ', ‘score': 28}, {‘name': ‘darl', ‘score': 28}, {‘name': ‘bob', ‘score': 18}]
[{‘name': ‘bob', ‘score': 18}, {‘name': ‘christ', ‘score': 28}, {‘name': ‘darl', ‘score': 28}, {‘name': ‘alice', ‘score': 38}]

3. 字典中混合list

d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}
# sort返回的是list,如果需要转为dict,再sorted前面套一个dict()就可以了
print(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) ))) # 对字符比较需要ord。如果是'123'字符串数字可以使用int。
# print(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) )))

[(‘Zhang', [‘E', 2]), (‘Du', [‘C', 2]), (‘Wang', [‘P', 3]), (‘Li', [‘M', 7]), (‘Zhe', [‘H', 7]), (‘Ma', [‘C', 9])]

4. 对字典中的多维list进行排序

d2 = {
  'Apple': [['44', 88], ['11', 33], ['22', 88]],
  'Banana': [['55', 43], ['11', 68], ['44', 22]],
  'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}
for key, value in d2.items():
  d2[key] = sorted(value, key=lambda x:(x[1], -int(x[0]))) # 按list第二列升序,相同则按第一列降序,参考二维list排序
print(d2)

{‘Apple': [[‘11', 33], [‘44', 88], [‘22', 88]], ‘Banana': [[‘44', 22], [‘55', 43], [‘11', 68]], ‘Orange': [[‘33', 22], [‘22', 22], [‘52', 41], [‘44', 42]]}

到此这篇关于Python sorted对list和dict排序的文章就介绍到这了,更多相关Python sorted对list和dict排序内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python排序函数sort()与sorted()的区别

    python 中sorted与sort有什么区别 sort(cmp=None, key=None, reverse=False) sorted(iterable, cmp=None, key=None, reverse=False) sort是容器的函数,用List的成员函数sort进行排序 sorted是Python的内建函数相同的参数,用built-in函数sorted进行排序 sorted(iterable,key=None,reverse=False),返回新的列表,对所有可迭代的对象均

  • Python使用sorted排序的方法小结

    本文实例讲述了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)) prin

  • Python中利用sorted()函数排序的简单教程

    排序算法 排序也是在程序中经常用到的算法.无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小.如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来.通常规定,对于两个元素x和y,如果认为x < y,则返回-1,如果认为x == y,则返回0,如果认为x > y,则返回1,这样,排序算法就不用关心具体的比较过程,而是根据比较结果直接排序. Python内置的sorted()函数就可以对list进行排序:

  • python sort、sorted高级排序技巧

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列. 1)排序基础 简单的升序排序是非常容易的.只需要调用sorted()方法.它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序. 复制代码 代码如下: >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] 你也可以使用list.sort()方法来排序,此时list本身将被修改.通常此方法不如s

  • Python 列表排序方法reverse、sort、sorted详解

    python语言中的列表排序方法有三个:reverse反转/倒序排序.sort正序排序.sorted可以获取排序后的列表.在更高级列表排序中,后两中方法还可以加入条件参数进行排序. reverse()方法 将列表中元素反转排序,比如下面这样 >>> x = [1,5,2,3,4] >>> x.reverse() >>> x [4, 3, 2, 5, 1] reverse列表反转排序:是把原列表中的元素顺序从左至右的重新存放,而不会对列表中的参数进行排序

  • python使用sorted函数对列表进行排序的方法

    本文实例讲述了python使用sorted函数对列表进行排序的方法.分享给大家供大家参考.具体如下: python提供了sorted函数用于对列表进行排序,并且可以按照正序或者倒序进行排列 #创建一个数字组成的列表 numbers = [5, 1, 4, 3, 2, 6, 7, 9] #输出排序后的数字数组 print sorted(numbers) #输出原始数组,并未被改变 print numbers my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "E

  • Python中sorted()排序与字母大小写的问题

    今天我在练习python时,对字典里的键用sorted排序时发现并没有按照预期排序 研究后发现字母大小写会影响排序 首先创建一个字典,键里面的首字母有大写有小写 favorite_digit = { 'john' : 4, 'Tom' : 5, 'Lisa' : 9, 'liu' : 5, 'alice' : 0, } for name in sorted(favorite_digit.keys()): print(name.title()) 运行后发现与预期不符合. Lisa Tom Alic

  • Python sorted排序方法如何实现

    在给列表排序时,sorted非常好用,语法如下: sorted(iterable[, cmp[,key[,reverse]]]) sorted定义如下: sorted( iterable[, cmp[, key[, reverse]]]) iterable:是可迭代类型类型; cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项; key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项; reverse:排序规则. reverse = True 或者 r

  • python中sort和sorted排序的实例方法

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列. 1)排序基础 简单的升序排序是非常容易的.只需要调用sorted()方法.它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] 你也可以使用list.sort()方法来排序,此时list本身将被修改.通常此方法不如sorted()方便,但

  • python3 sorted 如何实现自定义排序标准

    在 python2 中,如果想要自定义评价标准的话,可以这么做 def cmp(a, b): # 如果逻辑上认为 a < b ,返回 -1 # 如果逻辑上认为 a > b , 返回 1 # 如果逻辑上认为 a == b, 返回 0 pass a = [2,3,1,2] a = sorted(a, cmp) 但是在 python3 中,cmp 这个参数已经被移除了,那么在 python3 中应该怎么实现 python2 的 cmp 功能呢? import functools def cmp(a,

  • Python使用sorted对字典的key或value排序

    sorted函数 sorted(iterable,key,reverse) iterable 待排序的可迭代对象 key 对应的是个函数, 该函数用来决定选取用哪些值来进行排序 reverse 反转排序 对key排序 d: dict = {"p": 59, "o": 9, "s": 5, "a": 20, "z": 18} li: list = sorted(d.keys()) print(li) 执行结果

随机推荐