1、sort()与sorted()——数据排序
sort() 对数据原地排序,sorted()创建原地副本。用法是:
obj.sort();
obj2 = sorted(obj1)
>>> 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()可创建一个新集合。
sorted(集合) 可以返回一个列表对象。
>>> m = [1,2,1] >>> m [1, 2, 1] >>> m = {1,2,3,1} >>> m set([1, 2, 3]) >>> s=set([8,1,2,8]) >>> s set([8, 1, 2]) >>> sorted(s) [1, 2, 8]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]
4、列表的pop操作
>>> a= [2,3,4,1] >>> a.pop(0) 2 >>> a [3, 4, 1] >>>