Python列表排序
来源:互联网 发布:网络推广计划方案 编辑:程序博客网 时间:2024/06/05 04:49
【一】sort()函数和sort(reverse=True)
- 使用方法sort()对列表进行永久排序,sort()方法是按照字母或者数字的顺序来进行排列的,并且排序之后不会恢复到原始排序状态,但可以重新排序,如果向sort()方法中传入参数reverse=True,就可以倒着排序。
例如:
cars=["bmw","audi","toyota","porsche"]
print(cars)
cars.sort()#按照顺序排序
print(cars)
cars.sort(reverse=True)#倒着排序
print(cars)
num=[3,1,2,4,5,8,6,7]
num.sort()
print(num)
输出:
['bmw', 'audi', 'toyota', 'porsche']
['audi', 'bmw', 'porsche', 'toyota']
['toyota', 'porsche', 'bmw', 'audi']
[1, 2, 3, 4, 5, 6, 7, 8]
【二】sorted()函数
- 使用函数sorted()对列表进行临时排序,这只是临时的排序,可以恢复原来的顺序,同样可以倒着排序
cars=["bmw","audi","toyota","porsche"]
print(cars)
print(sorted(cars))
print(cars)
print(sorted(cars,reverse=True))
num=[3,1,2,4,5,8,6,7]
num.sort()
print(num)
输出:
['bmw', 'audi', 'toyota', 'porsche']
['audi', 'bmw', 'porsche', 'toyota']
['bmw', 'audi', 'toyota', 'porsche']
['toyota', 'porsche', 'bmw', 'audi']
[1, 2, 3, 4, 5, 6, 7, 8]
【三】reverse()函数
- 使用reverse()函数可以对列表进行反转,而不是排序,也是永久的,如果要恢复原状态只需要再用一次reverse()函数就行了
例如:
cars=["bmw","audi","toyota","porsche"]
print(cars)
cars.reverse()
print(cars)
cars.reverse()
print(cars)
num=[3,1,2,4,5,8,6,7]
num.sort()
print(num)
输出:
['bmw', 'audi', 'toyota', 'porsche']
['porsche', 'toyota', 'audi', 'bmw']
['bmw', 'audi', 'toyota', 'porsche']
[1, 2, 3, 4, 5, 6, 7, 8]
【四】len()函数
- 使用len()函数可以快速获悉列表的长度,也就是一共有多少个元素
print(len(cars))
输出:
4
- Python 的列表排序
- python列表排序
- python列表排序
- Python字典、列表排序
- python 列表排序
- Python 的列表排序
- python列表排序
- Python大法列表排序
- Python 的列表排序
- python列表排序
- Python 的列表排序
- Python列表拷贝,排序
- python列表的排序
- Python列表排序
- Python 列表的排序
- python列表操作,排序
- Python的列表排序
- Python列表排序函数
- Raft 为什么是更易理解的分布式一致性算法
- hdu 1015 Safecracker
- ACM-9月7日周四周中训练心得
- G
- jQuery调用ajax返回json对象
- Python列表排序
- 000000
- 【Altium】原理图更新PCB时未改动元器件布局变动的问题
- Java NIO浅析
- CCF认证 201403-1 相反数
- node.js_中间件
- Spring Security 简单示例
- TimeQuest约束外设之诡异的Create Generated Clocks用法
- java 大数BigInteger总结