2016年11月15日 星期二

[Python]基礎篇1.4

資料型態
將會介紹python幾種常見的資料型態,像整數、浮點數、字串、清單、字典等等

1.4.1 整數與浮點數















1.4.2 布林值
True / False

1.4.3 字串(string)
>>>string = ''                                      #空字串
>>>string_a = 'h'                                #字串以''或""框住
>>>string_b = 'ello'
>>>string_a + string_b                      #字串間的串接
'hello'

另外我們可以用三雙引號(""")來製造跨行的字串
 (又稱:doc string (文件字串)
用三雙引號製造出的字串不僅能跨行
還可以保留他字面上的格式















如果要取出字串中某個字元

string[idex(索引)]

string[0:5]      #從index = 0 取到 index =4
string[:5]        #從index的開頭取到index = 4
string[5:]        #從index = 5 取到index的尾巴
string[2:8]      #從index = 2 取到 index = 7
string[:]          #簡易複製字串的方法





字串也能進行格式化


字串中有些特殊的字串叫跳脫字元(escape character)
print "hello\n"

\\       倒斜線
\'       單引號
\"      雙引號
\a      鈴響
\b      退格
\n      換行
\t       縮排

使用非英文的字串
#-*- coding: utf-8 -*-

1.4.4 清單 (List)
清單是一個序列(sequence),我們能夠存放任何型態的資料在清單之中
>>>lst = [ 'abc' , 27 , None]

取出元素    >>>lst[0]      'abc'
                    >>>lst[1]      27
                    >>>lst[2]      None
                    >>>lst[-1]     None
                    >>>lst[1:]     [27,None]
改變元素    >>>lst[1] = 28
加入元素    >>>lst.append('New')
彈出元素    >>>lst.pop(2)                            #第二個元素消失
排序元素    >>>lst.sort()

1.4.5 Tuple
Tuple is similiar with list, they are both sequences ,but the elements in the Tuple are static
for example:
>>>t=(2,4,5)
>>>t[0]
2
>>>t[1]=0
TypeError

We find that if we decide to change the element of Tuple, there is a type error.

Another point we need to know is:
if we want a tuple with single element, we are forced to add a comma,EX:
t=(1,)
because if we type t=(1), python will mislead to t=1


1.4.6 Dictionary{}

Is not a sequence. Is a corresponding data structure.


>>>dic = { 'name' : 'jack', 'age':27}
>>>dic['name']
'jack'
>>>dic['age']
27

we call 'name', 'age' --------key
             'jack', 27   ----------value


更改字典值:dic['key']=value_1
增加字典值:dic['key_1]=value_2

1.4.7 巢狀結構
person = ['jack',27,[1998, 09,30]}












1.4.8 使用群集的好處
score = [90,91,92,93]
total = sum(score)

1.4.9 可變與不可變
a=1
a=2
a是個參照,改變的是參照的位置

string = "abc"
string[1]='x'
TypeError

因為字串的內容是不可變的

字典的鍵是要是不可變的資料


































沒有留言:

張貼留言