17、怎样对简单列表元素排序
题目:
简单列表:元素类型不是复合类型(列表、元组、字典)
- 形式1:[20,50,10,40,30]
- 形式2:['bb','ee','aa','dd','cc']
知识点:
- 怎样原地排序?怎样不改变原列表排序?
- 怎样指定是升序还是降序?
思路:
1、使用sort()方法
结果:
- 升序
list1 = [20,50,10,40,30]
list1.sort(reverse=False)
list2 = ['bb','ee','aa','dd','cc']
list2.sort(reverse=False)
print(f"list1升序:{list1}")
print(f"list1升序:{list2}")
------------------------
list1升序:[10, 20, 30, 40, 50]
list1升序:['aa', 'bb', 'cc', 'dd', 'ee']
- 降序
list1 = [20,50,10,40,30]
list1.sort(reverse=True)
list2 = ['bb','ee','aa','dd','cc']
list2.sort(reverse=True)
print(f"list1升序:{list1}")
print(f"list1升序:{list2}")
--------------------------
list1升序:[50, 40, 30, 20, 10]
list1升序:['ee', 'dd', 'cc', 'bb', 'aa']