python標準數據類型
有六個標準的數據類型:
1、Number(數字)
2、String(字符串)
3、tuple(元組)
4、list(列表)
5、dict(字典)
6、Sets(集合)
python數據類型分類
可變數據:
字典、列表
不可變數據:
數字、字符串、元組、集合
python數據類型介紹
Number
python3支持float、int、complex、bool
在python3中只有一種類型int,表示長整型,沒有python2中的long
示例:
a,b,c,d = 1.1,1,1+3j,True
可以用type查看:
>>> map(lambda x:type(x),[1,1.1,1+3j,True])
[<type 'int'>, <type 'float'>, <type 'complex'>, <type 'bool'>]
也可以用instance:
>>> isinstance(1.1,float)
True
String字符串
字符串或串(String)是由數字、字母、下劃線組成的一串字符。
以字母、數字、下劃線組成的一串字符
它是編程語言中表示文本的類型
示例:
定義字符串:
>>>a = 'stringtype'
取出字符串:
>>>>>>a
'stringtype'
截取前5位字符:
>>>a[0:5] 從0開始,但截止到5之前
'strin'
截取最後一位字符:
>>>a[-1:]
'e'
列表
列表用“[]”賦值
列表是使用最頻繁的一種數據類型。
截取的方式也可以用【開始:結束】來截取
示例:
>>> data = [1,2,3,5,6,2,1,4]
>>> data[0:2]
[1, 2]
元組
元組用"()"標識。內部元素用逗號隔開。但是元組不能二次賦值,相當於只讀列表。
示例:
>>> a = (1,2,3,4,5)
>>>
>>> a[0:3]
(1, 2, 3)
嘗試改變,但是是失敗的:
>>> a[2] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
字典
列表是有序的對象集合,字典是無序的對象集合。
兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。
字典用"{ }"標識。字典由索引(key)和它對應的值value組成。
示例:
>>> a = {'a':'b','c':'d','b':'a'}
>>> a
{'a': 'b', 'c': 'd', 'b': 'a'}
也可以用dict函數賦值:
>>> a = dict([('a','b')])
>>> a
{'a': 'b'}
創建空字典使用:
a = {}
或
a = dict()