簡單介紹Python中的幾種資料型別
大體上把Python中的資料型別分為如下幾類:
Number(數字) 包括int,long,float,complex
String(字串) 例如:hello,"hello",hello
List(列表) 例如:[1,2,3],[1,2,3,[1,2,3],4]
Dictionary(字典) 例如:{1:"nihao",2:"hello"}
Tuple(元組) 例如:(1,2,3,abc)
Bool(布林) 包括True、False
?
由於Python中認為所有的東西都是物件,所以Python不用像其它一些高階語言那樣主動宣告一個變數的型別。
例如我要給一個變數i賦值100,python的實現 :
i=100
|
C#的實現:
?1 |
int i
= 100;
|
下面一一簡單介紹這幾種資料型別
數字型別
int和long
之所以要把int和long放在一起的原因是python3.x之後已經不區分int和long,統一用int。python2.x還是區分的。下面我以Python2.7為例:
?>>> i = 10 >>> type(i) <type 'int'> >>> i=10000000000 >>> type(i) <type 'long'>
那麼為什麼10就是int,10000000000就是long呢,當然這就和int的最大值有關了,int型別的最大值為231-1,即2147483647,也可以用sys.maxint。
?>>> 2**31-1
2147483647L
>>> sys.maxint
2147483647
為什麼用上面的方法求的值就是long型的呢(數字後面加‘L'表示是long型),因為2**31的值為2147483648,這個值是一個long型,用一個long型減去1,結果還是一個long,但實際上int型的最大值就是2147483647
?>>> type(2147483647) <type 'int'> >>> type(2147483648) <type 'long'>
float型別
float型別和其它語言的float基本一致,浮點數,說白了,就是帶小數點的數,精度與機器相關。例如:
?>>> i = 10000.1212
>>> type(i)
<type 'float'>
complex:複數型別,具體含義及用法可自行檢視相關文件。
字串型別
字串的宣告有三種方式:單引號、雙引號和三引號(包括三個單引號或三個雙引號)。例如:
?>>> str1 = 'hello world'
>>> str2 = "hello world"
>>> str3 = '''hello world'''
>>> str4 = """hello world"""
>>> print str1
hello world
>>> print str2
hello world
>>> print str3
hello world
>>> print str4
hello world
Python中的字串有兩種資料型別:str型別和unicode型別。str型別採用的ASCII編碼,也就是說它無法表示中文。unicode型別採用unicode編碼,能夠表示任意字元,包括中文及其它語言。並且python中不存在像c語言中的char型別,就算是單個字元也是字串型別。字串預設採用的ASCII編碼,如果要顯示宣告為unicode型別的話,需要在字串前面加上'u'或者'U'。例如:
?>>> str1 = "hello"
>>> print str1
hello
>>> str2 = u"中國"
>>> print str2
中國
由於專案中經常出現對字串的操作,而且由於字串編碼問題出現的問題很多,下面,來說一下關於字串的編碼問題。在與python打交道的過程中經常會碰到ASCII、Unicode和UTF-8三種編碼。具體的介紹請參見這篇文章。我簡單的理解就是,ASCII編碼適用英文字元,Unicode適用於非英文字元(例如中文、韓文等),而utf-8則是一種儲存和傳送的格式,是對Uncode字元的再編碼(以8位為單位編碼)。例如:
?u = u'漢'
print repr(u) # u'\u6c49'
s = u.encode('UTF-8')
print repr(s) # '\xe6\xb1\x89'
u2 = s.decode('UTF-8')
print repr(u2) # u'\u6c49'
解釋:宣告unicode字串”漢“,它的unicode編碼為”\u6c49“,經過utf-8編碼轉換後,它的編碼變成”\xe6\xb1\x89“。
對於編碼的經驗總結:
1.在python檔案頭宣告編碼格式 ;
#-*- coding: utf-8 -*-
2.將字串統一宣告為unicode型別,即在字串前加u或者U;
3.對於檔案讀寫的操作,建議適用codecs.open()代替內建的open(),遵循一個原則,用哪種格式寫,就用哪種格式讀;
假設在一個以ANSI格式儲存的文字檔案中有“中國漢字”幾個字,如果直接用以下程式碼,並且要在GUI上或者在一個IDE中打印出來(例如在sublime text中,或者在pydev中列印),就會出現亂碼或者異常,因為codecs會依據文字本身的編碼格式讀取內容:
?f = codecs.open("d:/test.txt")
content = f.read()
f.close()
print content
改用如下方法即可(只對中文起作用):
?# -*- coding: utf-8 -*-
import codecs
f = codecs.open("d:/test.txt")
content = f.read()
f.close()
if isinstance(content,unicode):
print content.encode('utf-8')
print "utf-8"
else:
print content.decode('gbk').encode('utf-8')
列表型別
列表是一種可修改的集合型別,其元素可以是數字、string等基本型別,也可以是列表、元組、字典等集合物件,甚至可以是自定義的型別。其定義方式如下:
?>>> nums = [1,2,3,4]
>>> type(nums)
<type 'list'>
>>> print nums
[1, 2, 3, 4]
>>> strs = ["hello","world"]
>>> print strs
['hello', 'world']
>>> lst = [1,"hello",False,nums,strs]
>>> type(lst)
<type 'list'>
>>> print lst
[1, 'hello', False, [1, 2, 3, 4], ['hello', 'world']]
用索引的方式訪問列表元素,索引從0開始,支援負數索引,-1為最後一個.
>>> lst = [1,2,3,4,5]
>>> print lst[0]
1
>>> print lst[-1]
5
>>> print lst[-2]
4
?
支援分片操作,可訪問一個區間內的元素,支援不同的步長,可利用分片進行資料插入與複製操作
?nums = [1,2,3,4,5]
print nums[0:3] #[1, 2, 3] #前三個元素
print nums[3:] #[4, 5] #後兩個元素
print nums[-3:] #[3, 4, 5] #後三個元素 不支援nums[-3:0]
numsclone = nums[:]
print numsclone #[1, 2, 3, 4, 5] 複製操作
print nums[0:4:2] #[1, 3] 步長為2
nums[3:3] = ["three","four"] #[1, 2, 3, 'three', 'four', 4, 5] 在3和4之間插入
nums[3:5] = [] #[1, 2, 3, 4, 5] 將第4和第5個元素替換為[] 即刪除["three","four"]
支援加法和乘法操作
lst1 = ["hello","world"]
lst2 = ['good','time']
print lst1+lst2 #['hello', 'world', 'good', 'time']
print lst1*5 #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world']
?
列表所支援的方法,可以用如下方式檢視列表支援的公共方法:
?列表轉換為迭代器。
所謂的迭代器就是具有next方法(這個方法在呼叫時不需要任何引數)的物件。在呼叫next方法時,迭代器會返回它的下一個值。如果next方法被呼叫,但迭代器沒有值可以返回,就會引發一個StopIteration異常。迭代器相對於列表的優勢在於,使用迭代器不必一次性將列表加入記憶體,而可以依次訪問列表的資料。
依然用上面的方法檢視迭代器的公共方法:
lst = [1,2,3,4,5]
lstiter = iter(lst)
print [x for x in dir(numiter) if not x.startswith("__")]
>>>['next']
沒錯,只有next一個方法,對於一個迭代器,可以這樣操作:
?lst = [1,2,3,4,5]
lstiter = iter(lst)
for i in range(len(lst)):
print lstiter.next() #依次列印
1
2
3
4
5
元組型別
元組型別和列表一樣,也是一種序列,與列表不同的是,元組是不可修改的。元組的宣告如下:
lst = (0,1,2,2,2)
lst1=("hello",)
lst2 = ("hello")
print type(lst1) #<type 'tuple'> 只有一個元素的情況下後面要加逗號 否則就是str型別
print type(lst2) #<type 'str'>
?
字典型別
字典型別是一種鍵值對的集合,類似於C#中的Dictionary<object,object>或js中的json物件。其初始化方法如下:
?dict1 = {}
print type(dict1) #<type 'dict'> 宣告一個空字典
dict2 = {"name":"kitty","age":18} #直接宣告字典型別
dict3 = dict([("name","kitty"),("age",18)]) #利用dict函式將列表轉換成字典
dict4 = dict(name='kitty',age=18) #利用dict函式通過關鍵字引數轉換為字典
dict5 = {}.fromkeys(["name","age"]) #利用fromkeys函式將key值列表生成字典,對應的值為None {'age': None, 'name': None}
字典基本的操作方法:
?#【新增元素】
dict1 = {}
dict1["mykey"] = "hello world" #直接給一個不存在的鍵值對賦值 即時新增新元素
dict1[('my','key')] = "this key is a tuple" #字典的鍵可以是任何一中不可變型別,例如數字、字串、元組等
#【鍵值對個數】
print len(dict1)
#【檢查是否含有鍵】
print "mykey" in dict1 #True 檢查是否含有鍵為mykey的鍵值對
print "hello" in dict1 #False
#【刪除】
del dict1["mykey"] #刪除鍵為mykey的鍵值對
繼續利用上面的方法檢視字典的所有公共方法:
>>> [x for x in dir({}) if not x.startswith("__")]
['clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
dict.clear() 刪除字典中所有元素
dict.copy() 返回字典(淺複製)的一個副本
dict.get(key,default=None) 對字典dict 中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default 的值(注意,引數default 的預設值為None)
dict.has_key(key) 如果鍵(key)在字典中存在,返回True,否則返回False. 在Python2.2版本引入in 和not in 後,此方法幾乎已廢棄不用了,但仍提供一個 可工作的介面。
dict.items() 返回一個包含字典中(鍵, 值)對元組的列表
dict.keys() 返回一個包含字典中鍵的列表
dict.values() 返回一個包含字典中所有值的列表
dict.iter() 方法iteritems(), iterkeys(), itervalues()與它們對應的非迭代方法一樣,不同的是它們返回一個迭代器,而不是一個列表。
dict.pop(key[, default]) 和方法get()相似,如果字典中key 鍵存在,刪除並返回dict[key],如果key 鍵不存在,且沒有給出default 的值,引發KeyError 異常。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。
布林型別
布林型別即True和False,和其它語言中的布林型別基本一致。下面列出典型的布林值
?print bool(0) #False
print bool(1) #True
print bool(-1) #True
print bool([]) #False
print bool(()) #False
print bool({}) #False
print bool('') #False
print bool(None) #False
i=100
|