溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python有哪幾種數(shù)據(jù)類型

發(fā)布時間:2020-07-14 15:32:35 來源:億速云 閱讀:209 作者:Leah 欄目:編程語言

python有哪幾種數(shù)據(jù)類型?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

python數(shù)據(jù)類型有八種,分別是:數(shù)字類型(int和long)、float類型、復(fù)數(shù)類型(complex)、字符串類型、列表類型、元組類型、字典類型、布爾類型(True和False)。

python數(shù)據(jù)類型有以下八種

數(shù)字類型

int和long

之所以要把int和long放在一起的原因是python3.x之后已經(jīng)不區(qū)分int和long,統(tǒng)一用int。python2.x還是區(qū)分的。下面我以Python2.7為例:

>>> i = 10  
>>> type(i)  
<type 'int'>
>>> i=10000000000  
>>> type(i)  
<type 'long'>

那么為什么10就是int,10000000000就是long呢,當(dāng)然這就和int的最大值有關(guān)了,int類型的最大值為231-1,即2147483647,也可以用sys.maxint。

>>> 2**31-1  
2147483647L  
>>> sys.maxint  
2147483647

為什么用上面的方法求的值就是long型的呢(數(shù)字后面加‘L’表示是long型),因為2**31的值為2147483648,這個值是一個long型,用一個long型減去1,結(jié)果還是一個long,但實際上int型的最大值就是2147483647

>>> type(2147483647)  
<type 'int'>  
>>> type(2147483648)  
<type 'long'>

float類型

float類型和其它語言的float基本一致,浮點數(shù),說白了,就是帶小數(shù)點的數(shù),精度與機(jī)器相關(guān)。例如:

>>> i = 10000.1212  
>>> type(i)  
<type 'float'>

complex:復(fù)數(shù)類型,具體含義及用法可自行查看相關(guān)文檔。

字符串類型

字符串的聲明有三種方式:單引號、雙引號和三引號(包括三個單引號或三個雙引號)。例如:

>>> 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中的字符串有兩種數(shù)據(jù)類型:str類型和unicode類型。str類型采用的ASCII編碼,也就是說它無法表示中文。

unicode類型采用unicode編碼,能夠表示任意字符,包括中文及其它語言。

并且python中不存在像c語言中的char類型,就算是單個字符也是字符串類型。字符串默認(rèn)采用的ASCII編碼,如果要顯示聲明為unicode類型的話,需要在字符串前面加上'u'或者'U'。例如:

>>> str1 = "hello"  
>>> print str1  
hello  
>>> str2 = u"中國"  
>>> print str2  
中國

由于項目中經(jīng)常出現(xiàn)對字符串的操作,而且由于字符串編碼問題出現(xiàn)的問題很多,下面,來說一下關(guān)于字符串的編碼問題。

在與python打交道的過程中經(jīng)常會碰到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“,經(jīng)過utf-8編碼轉(zhuǎn)換后,它的編碼變成”\xe6\xb1\x89“。

對于編碼的經(jīng)驗總結(jié):

1.在python文件頭聲明編碼格式 ;

#-*- coding: utf-8 -*-

2.將字符串統(tǒng)一聲明為unicode類型,即在字符串前加u或者U;

3.對于文件讀寫的操作,建議適用codecs.open()代替內(nèi)置的open(),遵循一個原則,用哪種格式寫,就用哪種格式讀;

假設(shè)在一個以ANSI格式保存的文本文件中有“中國漢字”幾個字,如果直接用以下代碼,并且要在GUI上或者在一個IDE中打印出來(例如在sublime text中,或者在pydev中打印),就會出現(xiàn)亂碼或者異常,因為codecs會依據(jù)文本本身的編碼格式讀取內(nèi)容:

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')

列表類型

列表是一種可修改的集合類型,其元素可以是數(shù)字、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開始,支持負(fù)數(shù)索引,-1為最后一個.

>>> lst = [1,2,3,4,5]  
>>> print lst[0]  
>>> print lst[-1]  
 
>>> print lst[-2]

支持分片操作,可訪問一個區(qū)間內(nèi)的元素,支持不同的步長,可利用分片進(jìn)行數(shù)據(jù)插入與復(fù)制操作

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]  復(fù)制操作  
  
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 x>y 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】  刪除一個元素,并返回此元素的值 支持索引 默認(rèn)為最后一個  
x = lst.pop()  
print x,lst     #hello [1, 2, 3, 4, 5, 6]  #默認(rèn)刪除最后一個元素  
x = lst.pop(0)  
print x,lst     #1 [2, 3, 4, 5, 6]  刪除第一個元素  
  
#【count】  返回一個元素出現(xiàn)的次數(shù)  
print lst.count(2)    #1     
  
#【extend】  擴(kuò)展列表  此方法與“+”操作的不同在于此方法改變原有列表,而“+”操作會產(chǎn)生一個新列表  
lstextend = ["hello","world"]  
lst.extend(lstextend)  
print lst           #[2, 3, 4, 5, 6, 'hello', 'world']  在lst的基礎(chǔ)上擴(kuò)展了lstextend進(jìn)來   
  
#【index】  返回某個值第一次出現(xiàn)的索引位置,如果未找到會拋出異常  
print lst.index("hello")  #5      
  
#print lst.index("kitty") #ValueError: 'kitty' is not in list  出現(xiàn)異常  
  
  
#【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】  意為反轉(zhuǎn) 沒錯 就是將列表元素倒序排列,無返回值  
print lst        #[2, 3, 4, 5, 6, 'world']  
lst.reverse()   
print lst        #[2, 3, 4, 5, 6, 'world']  
  
  
#【sort】 排序  
print lst    #由于上面的反轉(zhuǎn) 目前排序為 ['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]

列表轉(zhuǎn)換為迭代器。

所謂的迭代器就是具有next方法(這個方法在調(diào)用時不需要任何參數(shù))的對象。在調(diào)用next方法時,迭代器會返回它的下一個值。如果next方法被調(diào)用,但迭代器沒有值可以返回,就會引發(fā)一個StopIteration異常。迭代器相對于列表的優(yōu)勢在于,使用迭代器不必一次性將列表加入內(nèi)存,而可以依次訪問列表的數(shù)據(jù)。

依然用上面的方法查看迭代器的公共方法:

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函數(shù)將列表轉(zhuǎn)換成字典  
  
dict4 = dict(name='kitty',age=18)           #利用dict函數(shù)通過關(guān)鍵字參數(shù)轉(zhuǎn)換為字典  
  
dict5 = {}.fromkeys(["name","age"])      #利用fromkeys函數(shù)將key值列表生成字典,對應(yīng)的值為None   {'age': None, 'name': None}  
字典基本的操作方法:
#【添加元素】    
dict1 = {}  
dict1["mykey"] = "hello world"     #直接給一個不存在的鍵值對賦值 即時添加新元素  
  
dict1[('my','key')] = "this key is a tuple"   #字典的鍵可以是任何一中不可變類型,例如數(shù)字、字符串、元組等  
  
#【鍵值對個數(shù)】  
print len(dict1)  
  
#【檢查是否含有鍵】  
print "mykey" in dict1         #True  檢查是否含有鍵為mykey的鍵值對  
print "hello" in dict1         #False  
  
#【刪除】  
del dict1["mykey"]           #刪除鍵為mykey的鍵值對

繼續(xù)利用上面的方法查看字典的所有公共方法:

>>> [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()                          返回字典(淺復(fù)制)的一個副本  
  
dict.get(key,default=None)     對字典dict 中的鍵key,返回它對應(yīng)的值value,如果字典中不存在此鍵,則返回default 的值(注意,參數(shù)default 的默認(rèn)值為None)  
  
dict.has_key(key)                 如果鍵(key)在字典中存在,返回True,否則返回False. 在Python2.2版本引入in 和not in 后,此方法幾乎已廢棄不用了,但仍提供一個 可工作的接口。  
  
dict.items()                         返回一個包含字典中(鍵, 值)對元組的列表  
  
dict.keys()                          返回一個包含字典中鍵的列表  
  
dict.values()                        返回一個包含字典中所有值的列表  
  
dict.iter()                            方法iteritems(), iterkeys(), itervalues()與它們對應(yīng)的非迭代方法一樣,不同的是它們返回一個迭代器,而不是一個列表。  
  
dict.pop(key[, default])         和方法get()相似,如果字典中key 鍵存在,刪除并返回dict[key],如果key 鍵不存在,且沒有給出default 的值,引發(fā)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

看完上述內(nèi)容,你們掌握python有哪幾種數(shù)據(jù)類型的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI