python常用資料結構

來源:互聯網
上載者:User

標籤:get   統計   元素   數組排序   javascrip   rom   list   重複   for   

0. 字典初始化

d = {‘a’:1,’b’:2}

或 d={}

d[‘a’] = 1

d[‘b’] = 2

是不是和json格式資料很相似,文法和JavaScript又很相似

 

1. 變數接受序列分解:

p = (3.14,8.23)

X,Y = p

print(x,y)

3.14,8.23

 

2. Collections.deque 固定長度隊列。

>>> from collections import deque

>>> p = deque(maxlen = 2)

>>> p.append(3.14)

>>> p.append(8.23)

>>> p

deque([3.14, 8.23], maxlen=2)

 

3. heapq 最大值最小值。

>>> import heapq

>>> p = [3.14,8.23,7.10]

>>> heapq.nlargest(1,p)

[8.23]

>>> heapq.nsmallest(1,p)

[3.14]

 

 

5.找出兩個字典相同鍵 和相同項

>>> from collections import OrderedDict

>>> d = {}

>>> d[‘a‘] = 1

>>> d[‘c‘] = 3

>>> d[‘b‘] = 2

>>> dd = {}

>>> dd[‘a‘] = 3

>>> dd[‘e‘] = 5

>>> dd[‘b‘] = 2

>>> d.keys() & dd.keys()

{‘a‘, ‘b‘}

>>> d.items() & dd.items()

{(‘b‘, 2)}

 

6 去除數組或字典值重複的元素 set

>>> d ={1,1,2,2,3,3,4,5}

>>> set(d)

{1, 2, 3, 4, 5}

 

7 截取數組元素

>>> d = [1,1,2,2,3,3,4,5]

>>> d[2:4]

[2, 2]

>>> d[2:5]

[2, 2, 3]

 

8 統計元素出現次數Counter.most_common。

>>> d = [1,1,1,2,2,4,5]

>>> from collections import Counter

>>> master = Counter(d).most_common(2)

>>> print(master)

[(1, 3), (2, 2)]

 

4. collections.OrderedDict 有序字典

>>> from collections import OrderedDict

>>> d = OrderedDict()

>>> d[‘a‘] = 1

>>> d[‘c‘] = 3

>>> d[‘b‘] = 2

>>> print(d)

OrderedDict([(‘a‘, 1), (‘c‘, 3), (‘b‘, 2)])

 

9.數組排序 operator.itemgetter

>>> from operator import itemgetter

>>> d = [2,1,5,4,3]

>>> sorted(d)

[1, 2, 3, 4, 5]

 

10.字典排序 sort

>>> from operator import itemgetter

>>> p = [{‘x‘:‘3‘,‘y‘:‘3‘},{‘x‘:‘4‘,‘y‘:‘4‘},{‘x‘:‘2‘,‘y‘:‘2‘},{‘x‘:‘1‘,‘y‘:‘1‘}]

>>> p.sort(key=itemgetter(‘x‘))

>>> print(p)

[{‘x‘: ‘1‘, ‘y‘: ‘1‘}, {‘x‘: ‘2‘, ‘y‘: ‘2‘}, {‘x‘: ‘3‘, ‘y‘: ‘3‘}, {‘x‘: ‘4‘, ‘y‘: ‘4‘}]

 

11. lambda 運算式

>>> p = [{‘x‘:‘3‘,‘y‘:‘3‘},{‘x‘:‘4‘,‘y‘:‘4‘},{‘x‘:‘2‘,‘y‘:‘2‘},{‘x‘:‘1‘,‘y‘:‘1‘}]

>>> pLamb = [n[‘x‘] > ‘2‘ for n in p]

>>> print(pLamb)

[True, True, False, False]

 

12 compress 與 11項 結合使用。

>>> from itertools import compress

>>> list(compress(p,pLamb))

[{‘x‘: ‘3‘, ‘y‘: ‘3‘}, {‘x‘: ‘4‘, ‘y‘: ‘4‘}]

 

13.邏輯上合并對象

>>> p = {‘x‘:1,‘y‘:2}

>>> p2 = {‘y‘:3,‘z‘:4}

>>> from collections import ChainMap

>>> c = ChainMap(p,p2)

>>> print(c)

ChainMap({‘x‘: 1, ‘y‘: 2}, {‘y‘: 3, ‘z‘: 4})

>>> list(c.keys())

[‘x‘, ‘z‘, ‘y‘]

python常用資料結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.