2014年10月28日 星期二

python data structure note

Python筆記整理(Python 3.4)
Reference

Python tutorial

http://www.codedata.com.tw/python/python-tutorial-the-2nd-class-2-container-flow-for-comprehension/


運算子
>>> 17 / 3 # classic division returns a float ,單斜線浮點數
5.666666666666667

>>> 17 // 3 # floor division discards the fractional part,雙斜線浮點數整數
5

>>> 17 % 3 # the % operator returns the remainder of the division, 百分比餘數
2

>>> 5 ** 2 # 5 squared,雙星號平方
25

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _ # 變數_,可以用來表示最後的運算結果
113.0625

>>> a = 5
>>> a += 1 # 連加不使用++, 而是+=
>>> a
6


字串string
字串可以用單引號或是雙引號來表示,反斜線用來保護要印出的引號
>>> 'spam eggs' # single quotes
'spam eggs'
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> "\"Yes,\" he said."
'"Yes," he said.'

r來避免固定字
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name

印出多行可使用"""...""" or '''…'''
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

字串可以用加號來連接,用星號來複製
>>> 3 * 'un' + 'ium'
'unununium'

字串陣列引數可以有正負號
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[-2:] # characters from the second-last (included) to the end
'on'

陣列裡的數值無法被改變(immutable)
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment

可以用len()來偵測字串長度
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34


串列List(mutable),string享有共同操作
跟字元陣列一樣有正負號的引數,也可以用加號連接,用星號來複製,len來偵測長度
不一樣的是他的數值可以被改變
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

可以形成二維
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

list還有下列函式可以使用
>>> a = [1,4,2,6]
>>> a.append(3) # 增加數值
>>> a
[1, 4, 2, 6, 3]
>>> a.remove(4) # 移除數值
>>> a
[1, 2, 6, 3]
>>> a.pop() # 移除最後一位的數值
3
>>> a
[1, 2, 6]
>>> a.sort() # 排序
>>> a
[1, 2, 6]
>>> a.reverse() # 順序顛倒
>>> a
[6, 2, 1]
>>>
>>> a.index(1) # 列出數值6index
2
>>> del a[0] # 移除引數0
>>> a
[2, 1]
>>>


List 也可以當作queues來用
>>> 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'])

list還有更多的延伸功能,可以看一下這裡https://docs.python.org/3/tutorial/datastructures.html
5.1.1-5.1.4

Range()
代表由0開始到i-1
>>> for i in range(5):
... print(i)
...
0
1
2
3
4

如果range裡面有三個變數,最後一個表示間隔
range(5, 10)
5 through 9

range(0, 10, 3)
0, 3, 6, 9

range(-10, -100, -30)
-10, -40, -70


Tuple (immutable)
tuple內的數值是不可被改變的,可以用分號或是括號來表示
>>> t = 123,456,'hihi'
>>> t[1]
456
>>> t[1] = 123

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
t[1] = 123
TypeError: 'tuple' object does not support item assignment
>>> t
(123, 456, 'hihi')
>>>

因為tuple是不可變動的,所以要對tuple做變動的話,要先將其轉成list
>>> t = 2,5,4,8,6
>>> t
(2, 5, 4, 8, 6)
>>> t.sort()

Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
t.sort()
AttributeError: 'tuple' object has no attribute 'sort'
>>> t1 = list(t)
>>> t1.sort()
>>> t1
[2, 4, 5, 6, 8]
>>>

其他更多有關tuple的資訊可以看這http://openhome.cc/Gossip/Python/TupleType.html


Sets無序群集
其牽涉到物件相等性(hashable),要建立一個set必須用{}
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
>>> 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 either a or b
{'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'}


Dict
其是將keyvalue對應的物件,也是hashable,可用list(d.keys())sorted(d.keys())
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

其他更多有關setdict的範例可以看這5.6
https://docs.python.org/3/tutorial/datastructures.html

因為python有這麼方便的listtuple,使用者可以更方便的操控資料型態,把時間用在刀口上!!!!




沒有留言:

張貼留言