1、sort()与sorted()——数据排序
sort() 对数据原地排序,sorted()创建原地副本。用法是:
obj.sort();
obj2 = sorted(obj1)
<pre name="code" class="python">>>> a = [2,7,5,1,9] >>> b = sort(a) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> b = sort(a) NameError: name 'sort' is not defined >>> a.sort() >>> print a [1, 2, 5, 7, 9]
>>> a = [2,7,5,1,9] >>> b = a.sorted() Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> b = a.sorted() AttributeError: 'list' object has no attribute 'sorted' >>> b = sorted(a) >>> print a [2, 7, 5, 1, 9] >>> print b [1, 2, 5, 7, 9]
通过传递reverse = True,可以对sort()和sorted()传参,逆序排列。注意True首字母大写。
>>> a = [2,7,5,1,9] >>> b = sorted(a, reverse = True) >>> a,b ([2, 7, 5, 1, 9], [9, 7, 5, 2, 1]) >>> a.sort(reverse = True) >>> a [9, 7, 5, 2, 1]
2.python集合数据项——删除重复项
python提供了集合数据结构,显著特点是:数据无序,且不允许重复。用set()可创建一个新集合。
>>> m = [1,2,1] >>> m [1, 2, 1] >>> m = {1,2,3,1} >>> m set([1, 2, 3])3.创建新列表的方式——new_list = [ func for item in old_list ]
>>> a = [2,7,5,1,9] >>> b = [i/2 for i in a] >>> b [1, 3, 2, 0, 4]
版权声明:欢迎转载,转载请注明出处http://blog.csdn.net/ztf312/
《head first python》——理解数据:列表排序与集合
原文地址:http://blog.csdn.net/ztf312/article/details/47842679