python的内置高阶函数sorted

本文详细介绍了Python中列表排序的方法,包括使用sort()方法和sorted()函数进行正序和反序排序,以及如何根据自定义条件对复杂数据结构进行排序。通过实例展示了商品信息的排序技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.正序

1)
li =[4,2,5,62,7]
li.sort()  #使用排序方法
print(li)
运行结果:[2, 4, 5, 7, 62]

2)
li =[4,2,5,62,7]
a=sorted(li)	#使用函数排序
print(a)
运行结果:[2, 4, 5, 7, 62]

3)
li=[2,6,9,1,3,8]
li.sort(reverse=False)
print(li)
运行结果:[1, 2, 3, 6, 8, 9]

2.反序

1)
li=[2,6,9,1,3,8]
li.sort(reverse=True)
print(li)
运行结果:[9, 8, 6, 3, 2, 1]

2)
li =[4,2,5,62,7]
a=sorted(li,reverse=True)
print(a)
运行结果:[62, 7, 5, 4, 2]

练习:

1.按商品价格和数量排序
info = {
    # 商品名称 商品数量 商品价格
    ('apple1', 200, 132),
    ('apple2', 230, 25),
    ('apple3', 200, 106),
    ('apple4', 50, 96)
}

# 按数量排序
def sorted_by_count(x):
    return x[1]

print(sorted(info, key=sorted_by_count))


# 按价格排序
def sorted_by_price(x):
    return x[2]

print(sorted(info, key=sorted_by_price))	

# 先按数量再按价格
def sorted_by_count_price(x):
    return x[1], x[2]

print(sorted(info, key=sorted_by_count_price))

练习二:
给定一个整形数组,将数组中所有的0移动到末尾,非0项保持不变;
在原始数组上进行移动操作,勿创建新的数组;
输入:第一位是数组长度,后续每一位是数组记录;
40702输出:47200

n = ''.join(input().split())
li = [int(i) for i in n]

def move_zero(item):
    if item == 0:
        return 2
    else:
        return 1

print(sorted(li,key=move_zero))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值