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))