1. 抽取數組中不重複的資料
>>> a = [ x*2 for x in range(1,5) ]*2
>>> uniq = list(set(a))
[8, 2, 4, 6]
>>> uniq = sorted(set(a))
[2, 4, 6, 8]
>>> b={}
>>> for x in a:
… b[x]=1
>>> uniq = b.keys()
2. 去除在另一個數組中元素
>>> a = [ x*2 for x in range(1,5) ]
>>> b = [ x for x in a if x >3 ]
>>> aonly = [x for x in a if x not in b]
>>> a_set = set(a)
>>> b_set = set(b)
>>> aonly = list(a_set - b_set)
3. 數組排序
>>> def comp(x,y):
… if x>y:
… return -1
… elif x==y:
… return 0
… else :
… return 1
>>> unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]
>>> unsorted_list.sort(comp)
[88, 82, 81, 71, 67, 55, 46, 40, 10]
4. 兩個數組交、並操作
>>> a = [ x*2 for x in range(1,5) ]
[2, 4, 6, 8]
>>> b = [ x for x in range(3,7) ]
[3, 4, 5, 6]
>>> a_set = set(a)
>>> b_set = set(b)
# Union
>>> print list (a_set | b_set )
[2, 3, 4, 5, 6, 8]
#Intersection
>>> print list(a_set & b_set)
[4, 6]
#Difference
>>> print list(a_set ^ b_set)
[8, 2, 3, 5]
5. 數組函數map()、filter()、reduce()
a) map()
map(function,sequence)為每一個sequence的元素調用function(item) 並把傳回值組成一個數組。
>>>
>>> def fun(x): return x*x
>>> print map(fun,range(0,5))
[0, 1, 4, 9, 16]
使用map(None,list1,list2)可以快速把兩個數組變成元素對的一個數組
>>> print map(None,range(0,5),range(100,105))
[(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)]
b) filter()
filter(function,sequence)返回一個序列,包含了所有調用function(item)後傳回值為true的元素。
>>> unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]
>>> def fun(x): return x%2==0
>>> print filter(fun,unsorted_list)
[88, 82, 46, 40, 10]
c) reduce()
reduce(function,sequence)返回一個單值,首先以數組的前兩個元素調用函數function,在以傳回值和第三個元素為參數調用,依次執行下去。
例如,以下程式計算1到10的整數的和
>>> def add(x,y): return x+y
>>> print reduce(add,range(0,11))
55