Python中Array的常用操作(三)數組進階操作

來源:互聯網
上載者:User

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.