天天看點

Python基礎之:Python的資料結構

目錄

  • 簡介
  • 清單
    • 清單作為棧使用
    • 清單作為隊列使用
    • 清單推導式
    • del
  • 元組
  • 集合
  • 字典
  • 循環

不管是做科學計算還是編寫應用程式,都需要使用到一些基本的資料結構,比如清單,元組,字典等。

本文将會詳細講解Python中的這些基礎資料結構。

清單也就是list,可以用方括号來表示:

In [40]: ages = [ 10, 14, 18, 20 ,25]

In [41]: ages
Out[41]: [10, 14, 18, 20, 25]
           

list有一些非常有用的方法,比如append,extend,insert,remove,pop,index,count,sort,reverse,copy等。

舉個例子:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
           

棧的特點是後進先出,而清單為我們提供了append和pop方法,是以使用清單來實作棧是非常簡單的:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
           

隊列的特點是先進先出,但是使用清單在隊列頭部插入元素是很慢的,因為需要移動所有的元素。

我們可以使用

collections.deque

來快速的從兩端操作:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
           

要建立清單,通常的做法是使用for循環,來周遊清單,并為其設定值:

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
           

或者我們可以使用清單推導式來更加簡潔的生成清單:

squares = [x**2 for x in range(10)]
           

清單推導式的結構是由一對方括号所包含的以下内容:一個表達式,後面跟一個

for

子句,然後是零個或多個

for

if

子句。

清單推導式将會周遊for字句中的元素,并且使用表達式來求值,将生成的元素作為新的清單元素傳回。

看一個複雜點的:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
           

上面的表達式等價于:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
           

清單推導式還可以嵌套,假如我們有一個矩陣:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
           

可以使用下面的表達式将矩陣進行行列交換:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
           

或者使用更加簡單的zip函數:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
           

删除清單中的某個元素可以使用del。del可以删除清單中的某個特定的值,也可以删除切片,甚至删除整個清單:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

>>> del a
           

元組跟清單很類似,不同的是元組是不可變的。

元組是以小括号來表示的,或者可以不使用括号。

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
           

元組和List的操作很類似,都有切片和索引操作。

元組可以友善的進行解包:

>>> x, y, z = t
           

集合使用set函數或者花括号來表示的。

集合中的元素是不重複的,這個一點和java中的set很類似。

因為字典的表示也是花括号,是以如果你需要建立一個空集合的話,需要使用set,因為空的 {} 表示的是字典。

看一些集合的簡單例子:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
           

和清單一樣,集合也支援推導式:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
           

字典也是用花括号來表示的,不同的是字典中的元素是以 key:value的形式呈現的。

下面是字典的一些基本操作:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
           

除了花括号,還可以使用dict函數來建構字典:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
           

如果關鍵字是簡單的字元的話,可以直接這樣寫:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
           

同樣的推導式也可以使用:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
           

我們一般使用for語句來周遊集合或者字典,list等。

當我們周遊字典的時候,可以使用items()方法來同時擷取到key和value:

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
           

如果是清單,那麼可以使用enumerate 函數來擷取到index和value:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
           

之前我們還使用了zip函數,zip函數可以将多個序列中的元素一一比對:

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
           

本文已收錄于 http://www.flydean.com/06-python-data-structure/

最通俗的解讀,最深刻的幹貨,最簡潔的教程,衆多你不知道的小技巧等你來發現!

歡迎關注我的公衆号:「程式那些事」,懂技術,更懂你!

繼續閱讀