『Python』排序,列表中嵌套字典的排序

#-- encoding=utf-8 --

python3代码

import operator
一. 按字典值排序(默认为升序)
x = {1:2, 3:4, 4:3, 2:1, 0:0}

  1. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
    print sorted_x
    #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
    #如果要降序排序,可以指定reverse=True
  2. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
    print sorted_x
    #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
    二. 或者直接使用list的reverse方法将sorted_x顺序反转
    #sorted_x.reverse()

三. 更为常用的方法是,用lambda表达式
3. sorted_x = sorted(x.iteritems(), key=lambda x : x[1])
print sorted_x
#[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
4. sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
print sorted_x
#[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]

四. 包含字典dict的列表list的排序方法与dict的排序类似,如下:
x = [{‘name’:‘Homer’, ‘age’:39}, {‘name’:‘Bart’, ‘age’:10}]
sorted_x = sorted(x, key=operator.itemgetter(‘name’))
print sorted_x
#[{‘age’: 10, ‘name’: ‘Bart’}, {‘age’: 39, ‘name’: ‘Homer’}]
sorted_x = sorted(x, key=operator.itemgetter(‘name’), reverse=True)
print sorted_x
#[{‘age’: 39, ‘name’: ‘Homer’}, {‘age’: 10, ‘name’: ‘Bart’}]
sorted_x = sorted(x, key=lambda x : x[‘name’])
print sorted_x
#[{‘age’: 10, ‘name’: ‘Bart’}, {‘age’: 39, ‘name’: ‘Homer’}]
5. sorted_x = sorted(x, key=lambda x : x[‘name’], reverse=True)
print sorted_x
#[{‘age’: 39, ‘name’: ‘Homer’}, {‘age’: 10, ‘name’: ‘Bart’}]

pandas

你可能感兴趣的:(编程语言)