高阶函数——sorted

list.sort()和sorted()的对比

不同点:

list.sort()

li = [1,2,4,6,3]
li.sort()
print(li)
#sort()是在原有的内存空间内将原来的列表进行排列

在这里插入图片描述

sorted()

a = sorted(li)
print(a)
#sorted()是重新在一个新的内存空间中进行排序

在这里插入图片描述

相同点:

默认sort和sorted方法由小到大进行排序,reverse =True由大到小进行排序

a = sorted(li,reverse=True)
print(a)   

在这里插入图片描述

sorted中嵌套字典

d = {
    '003': {
        'name': 'apple1',
        'count': 100,
        'price': 50
    },
    '002': {
        'name': 'apple2',
        'count': 200,
        'price': 10
    }
}
print(sorted(d.items(), key=lambda x: x[1]['price']))
print(sorted(d.items(), key=lambda x: x[1]['count']))

在这里插入图片描述

sorted()函数举例

例一:

info = [
    # 商品名称   商品数量   商品价格
    ['apple1', 200, 32],
    ['apple4', 40, 12],
    ['apple3', 40, 2],
    ['apple2', 1000, 23]
]

print(sorted(info))

def sorted_by_count(x):
    return x[1]

def sorted_by_price(x):
    return x[2]

def sorted_by_count_price(x):
    return x[1], x[2]

print(sorted(info, key=sorted_by_count))
print(sorted(info, key=sorted_by_price))
print(sorted(info, key=sorted_by_count_price))

在这里插入图片描述

例二:
(2018-携程-春招题)题目需求:
给定一个整形数组,将数组中所有的0移动到末尾,非0项保持不变;
在原始数组上进行移动操作,勿创建新的数组;
输入:
第一行是数组长度,后续每一行是数组的一条记录;
4
0
7
0
2
输出:
调整后数组的内容;
7
2
0
0

n = int(input('数组长度:'))
li = [int(input()) for i in range(n)]
def move_zore(item):
    if item == 0:
        return 1
    else:
        return 0
for i in sorted(li,key=move_zore):
    print(i)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dodobibibi/article/details/84894550