python杂记

1:嵌套字典,排序
dict1 = {
'003':{
'name':'apple1',
'count':100,
'price':10
},
'002': {
'name': 'apple1',
'count': 200,
'price': 2
},
}
print(dict1.items())
运行结果:[('003', {'name': 'apple1', 'count': 100, 'price': 10}), ('002', {'name': 'apple1', 'count': 200, 'price': 2})]

print(sorted(dict1.items(), reverse=True, key=lambda x:x[1]["count"]))
运行结果:[('002', {'name': 'apple1', 'count': 200, 'price': 2}), ('003', {'name': 'apple1', 'count': 100, 'price': 10})]

2:有一个整数列表(10个元素),要求调整元素顺序(偶数在前,奇数在后)
import random
myLst = [random.randint(20, 50) for i in range(5)]
print(myLst)
print(sorted(myLst, key=lambda x: 0 if x%2==0 else 1))
print(sorted(myLst, key=lambda x: not x%2==0))
运行结果:
[41, 21, 36, 24, 30]
[36, 24, 30, 41, 21]
[36, 24, 30, 41, 21]
发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();