當前位置:成語大全網 - 新華字典 - Python中的幾種數據類型

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#的實現:

int i = 100;

下面壹壹簡單介紹這幾種數據類型

數字類型

int和long

之所以要把int和long放在壹起的原因是python3.x之後已經不區分int和long,統壹用int。python2.x還是區分的。下面我以Python2.7為例:

i = 10

type(i)

i=10000000000

type(i)

那麽為什麽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(2147483648)

float類型

float類型和其它語言的float基本壹致,浮點數,說白了,就是帶小數點的數,精度與機器相關。例如:

i = 10000.1212

type(i)

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) # uu6c49

s = u.encode(UTF-8)

print repr(s) # xe6xb1x89

u2 = s.decode(UTF-8)

print repr(u2) # uu6c49

解釋:聲明unicode字符串”漢“,它的unicode編碼為”u6c49“,經過utf-8編碼轉換後,它的編碼變成”xe6xb1x89“。

對於編碼的經驗總結:

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)

print nums

[1, 2, 3, 4]

strs = [hello,world]

print strs

[hello, world]

lst = [1,hello,False,nums,strs]

type(lst)

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]

列表所支持的方法,可以用如下方式查看列表支持的公***方法:

[x for x in dir([]) if not x.startswith(__)]

[append, count, extend, index, insert, pop, remove, reverse, sort]

def compare(x,y):

return 1 if xy else -1

#append 在列表末尾插入元素

lst = [1,2,3,4,5]

lst.append(6)

print lst #[1, 2, 3, 4, 5, 6]

lst.append(hello)

print lst #[1, 2, 3, 4, 5, 6]

#pop 刪除壹個元素,並返回此元素的值 支持索引 默認為最後壹個

x = lst.pop()

print x,lst #hello [1, 2, 3, 4, 5, 6] #默認刪除最後壹個元素

x = lst.pop(0)

print x,lst #1 [2, 3, 4, 5, 6] 刪除第壹個元素

#count 返回壹個元素出現的次數

print lst.count(2) #1

#extend 擴展列表 此方法與“+”操作的不同在於此方法改變原有列表,而“+”操作會產生壹個新列表

lstextend = [hello,world]

lst.extend(lstextend)

print lst #[2, 3, 4, 5, 6, hello, world] 在lst的基礎上擴展了lstextend進來

#index 返回某個值第壹次出現的索引位置,如果未找到會拋出異常

print lst.index(hello) #5

#print lst.index(kitty) #ValueError: kitty is not in list 出現異常

#remove 移除列表中的某個元素,如果待移除的項不存在,會拋出異常 無返回值

lst.remove(hello)

print lst #[2, 3, 4, 5, 6, world] hello 被移除

#lst.remove(kitty) #ValueError: list.remove(x): x not in list

#reverse 意為反轉 沒錯 就是將列表元素倒序排列,無返回值

print lst #[2, 3, 4, 5, 6, world]

lst.reverse()

print lst #[2, 3, 4, 5, 6, world]

#sort 排序

print lst #由於上面的反轉 目前排序為 [world, 6, 5, 4, 3, 2]

lst.sort()

print lst #排序後 [2, 3, 4, 5, 6, world]

nums = [10,5,4,2,3]

print nums #[10,5,4,2,3]

nums.sort(compare)

print nums #[2, 3, 4, 5, 10]

列表轉換為叠代器。

所謂的叠代器就是具有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) # 只有壹個元素的情況下後面要加逗號 否則就是str類型

print type(lst2) #

字典類型

字典類型是壹種鍵值對的集合,類似於C#中的Dictionary

dict1 = {}

print type(dict1) # 聲明壹個空字典

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