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]
>>> ``````