Home  >  Article  >  Backend Development  >  Python对列表排序的方法实例分析

Python对列表排序的方法实例分析

WBOY
WBOYOriginal
2016-06-10 15:12:291596browse

本文实例讲述了Python对列表排序的方法。分享给大家供大家参考。具体分析如下:

1、sort()函数

sort()函数使用固定的排序算法对列表排序。sort()函数对列表排序时改变了原来的列表,从而让其中的元素能按一定的顺序排列,而不是简单的返回一个已排序的列表副本。

注意sort()函数改变原来的列表,函数返回值是空值即None。因此,如果需要一个已排好序的列表副本,同时又要保留原有列表不变的时候,就不能直接简单的使用sort()函数。为了实现上述功能使用sort()的方法是:先获取列表X的副本Y,然后再对Y进行排序。代码如下:

x=[4,6,2,1,7,9,4]
y=x[:]
y.sort()
print x
print y

结果如下:

[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]

说明:调用x[:]得到的是包含了x所有元素的分片,这是一种很有效率的复制整个列表的方法。通过y=x简单的将x复制给y是没有用的,因为这样做就让x和y都指向了同一个列表了。

2、sorted()函数

另外一种获取已排序的列表副本的方法是使用sorted()函数。注意,sorted()函数可以用于任何可迭代的对象。

x=[4,6,2,1,7,9,4]
y=sorted(x)
print x
print y

结果:

[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn