日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python将元祖设为整形_python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍...

發布時間:2024/7/5 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python将元祖设为整形_python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對于python而言,一切事物都是對象,對象是基于類創建的,對象繼承了類的屬性,方法等特性

1.int

首先,我們來查看下int包含了哪些函數

#python3.x

dir(int)#['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

#python 2.x

dir(int)#['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

#__abs__() 絕對值輸出

num = 1result= num.__abs__()print(result)

num= -1result= num.__abs__()print(result)

__abs__() 絕對值輸出

1 num = -1

2 result = num.__add__(2)3

4 print(result)5

6 #打印結果將輸出 1

__add__加法

1 num = 5

2 result = num.__and__(2)3 print(result)4

5 #打印輸出為0

6 #0 0 0 0 0 1 0 1 5

7 #0 0 0 0 0 0 1 0 2

8 #相同位為1則為1,由于沒有相同位,所以5 & 2結果為0

__and__ 與&運算

1 #以下結果輸出都是True

2 num = 11

3 print(num.__bool__()) #True

4

5 num = -11

6 print(num.__bool__()) #True

7

8 #以下結果輸出都是 False

9 num =010 print(num.__bool__()) #False

11

12 num =None13 num =False14 print (num.__bool__()) #False

__bool__ 布爾值

#通過divmod函數可以實現將一個int類型對象除以另一個int對象得到一個兩個元素的列表,#列表左邊為除盡取整的值,第二個元素為取模的余數

num= 9result= num.__divmod__(2)print(result)#輸出(4,1)

__divmod__ 除法取整取模

num = 2result= num.__eq__(3)print(result)#打印結果為False#2 == 3 結果為假

result= num.__eq__(2)print(result)#打印結果為True#2 == 2 結果為真

__eq__ ==比較運算符

__eq__ ==比較運算符

num = 9

print(num.__float__())#打印結果為 9.0

__float__ 轉換為浮點數

num = int(181)

result= num.__floordiv__(9)print(result)#打印輸出20#地板除 //取整

__floordiv__地板除//

__floordiv__地板除//

num = int(181)

result= num.__getattribute__("bit_length")print(result)#打印輸出 #說明該數據類型num存在bit_length這個屬性,可以用于判斷對象是否擁有某種屬性

__getattribute__獲取對象屬性

num = int(181)print(num.__ge__(111))#打印輸出結果為True#因為181大于111,所以結果為真,該屬性用于判斷大于等于該屬性自身的方法,結果將返回真,否則為假

__ge__ 比較運算>=

num = 181

print(int.__invert__(num))#打印輸出-182

num= -180

print(int.__invert__(num))#打印輸出179

num= -181

print(int.__invert__(num))#打印輸出180

__invert__ 非~運算

num = -181result= num.__le__(111)print(result)#打印輸出結果為True#當傳人參數與對象本身相比較,只要對象小于或者等于傳人的參數,則結果為真,否則為假

__le__ 小于等于

num = -181result= num.__lshift__(1)print(result)#打印輸出結果為-362 ,即-181 *( 2**1)

result= num.__lshift__(2)print(result)#打印輸出結果為-724 ,即-181*(2**2)

#當傳入參數大于等于0時且對象本身不能為0,首先參數本身為2的指數冪運算,然后再與對象本身相乘結果則為左移最終結果

__lshift__左移運算

num = -181

print(num.__lt__(11))#打印輸出結果為True

#凡是對象比傳入的參數小,則結果為真,否則結果為假

__lt__小于

num = -181

print(num.__mod__(3))#打印輸出結果為2,因為-181除以3等于60,余數為2,所以結果為2

__mod__取模運算

num = 181

print(num.__mul__(2))#打印輸出結果為362,即181*2的結果

__mul__ 乘法運算

num = -181

print(int.__neg__(num))#打印結果為181,即-(-181),結果為181

__neg__一元運算減法

num = 181

print(num.__ne__(181))#打印結果為False

print(num.__ne__(11))#打印結果為True

#凡是傳入參數與對象本身不相等,則結果為真,否則為假

__ne__ 不等于比較

num = 18

print(num.__or__(7))#打印輸出結果為23#0 0 0 1 0 0 1 0 18#0 0 0 0 0 1 1 1 7#0 0 0 1 0 1 1 1 23

位的或運算,凡是相同位有一位為真,即為1,則結果為真,即1,然后所以最終結果為23

__or__ 或|運算

num = 9

print(num.__pow__(2))#打印輸出結果為81,即9**2

__pow__ 冪運算

num = 6

print(num.__rdivmod__(3))#返回結果(0,3) 左邊為余數,右邊為整除的結果

__rdivmod__ 與divmod返回的結果相反

#python 2.7

num = 1

print(num.__sizeof__())#打印輸出結果為24個字節,說明一個int類型默認就在內存中占用了24個字節大小

#python3.5

num = 1

print(num.__sizeof__())#打印輸出結果為28個字節,說明一個int類型數據默認在內存中占用了24個字節大小

__sizeof__ 計算數據類型占用內存大小

num = int(1111)

result= num.__str__()print(type(result))#打印輸出結果為#將int類型轉換為str數據類型

__str__ int轉換成str

num = int(9)print(num.__sub__(2))#打印輸出結果為7#對象本身減去傳入參數,得到最終的返回值

__sub__ 減法運算

num = 11

print(num.__truediv__(3))#打印輸出結果為3.6666666666666665#返回的數據類型為float,浮點型

__truediv__ 真除

num = 10

print(num.__xor__(6))#0 0 0 0 1 0 1 0 10#0 0 0 0 0 1 1 0 6#0 0 0 0 1 1 0 0 12

#同位比較,都是0則為假,都是1則為假,一真一假為真

__xor__ 異或^運算

num = 5

print(num.bit_length())#打印輸出結果為3

#0 0 0 0 0 1 0 1 #長度為3位

bit_length 顯示數據所占位長度

num = 2.3 - 2.5jresult= num.real #復數的實部

print(result) #打印輸出2.3

result = num.imag #復數的虛部

print(result) #打印輸出2.5j

result= num.conjugate() #返回該復數的共軛復數

print(result) #打印輸出(2.3+2.5j)

conjugate

num = 5

print(num.__format__("20"))#表示5前面講話有20個空格

__format__ 格式化輸出

print(int.from_bytes(bytes=b'1', byteorder='little')#打印輸出 49 ,即將字符1轉換為十進制

from_bytes 字符轉換十進制

num = 2result= num.to_bytes(5,byteorder='little')print(result)#打印輸出b'\x02\x00\x00\x00\x00'

for i inresult:print(i)#打印輸出2\n0\n0\n0\n0#\n表示回車

to_bytes int轉換為字節

2.str

1 #python3.5

2dir(str)3 #['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

4

5 #python2.7

6dir(str)7 #['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

strA = "hello"

print(strA.__add__("world"))#輸出hello world

__add__ 字符串拼接

strA = "hello"

print(strA.__contains__("h"))#True

print(strA.__contains__('hex'))#False

__contains__ 包含判斷

strA = "hello"

print(strA.__eq__('hello'))#True

print(strA.__eq__('hellq'))#False

__eq__ 字符串==比較

strA = "hello"

print(strA.__getattribute__('__add__'))#

#判斷對象是否包含傳入參數的屬性

__getattribute__獲取對象屬性

strA = "hello"

print(strA.__getitem__(0))#輸出下標為0的字符 h#超出下標會報錯的

__getitem__獲取對應字符

strA = "hello"

print(strA.__getnewargs__())#打印輸出 ('hello',)#將字符類型轉換為元組方式輸出

__getnewargs__轉換成元組

strA = "hello"

print(strA.__ge__('HELLO'))print(strA.__ge__('Hello'))print(strA.__ge__('hello'))#以上結果都為True,

print(strA.__ge__('hellq'))#以上結果為假

__ge__ 字符串比較

strA = 'Hello'

print(strA.__gt__('HellO'))#打印輸出True

#字符串比較的是傳入的參數每個字符首先得包含對象,其次如果字符串之間比較,大寫比小寫大,,如果傳入參數都為大寫,且對象也都為大寫,那么結果為假,字符串比較首先比較的是字符串是否相同,不相同則為假,再次每個字符進行比較,只要前面有一位大于對方,則不繼續比較了

#比如 HelLo與HEllo,首先兩個字符串都是一樣的,然后再比較第一位,第一位也一樣,再比較第二位,大寫比小寫大,所以第二個字符串大,就不會繼續比較下去了

__gt__ 字符串大于判斷

strA = "hello"

print(strA.__hash__())#-7842000111924627789

__hash__ 生成一個臨時的hash值

strA = "hello"result= strA.__iter__()for i inresult:print(i)#打印輸出#h#e#l#l#o

__iter__ 字符串迭代

strA = 'hello'

print(strA.__len__())#打印輸出結果為5

__len__ 判斷字符串長度

strA = 'Hello'

print(strA.__le__('ello'))#True

#字符串小于運算比較,先比較對象是否包含傳入參數,當包含則再比較相同位的字母,大小字母比小寫字母大,當前面有一位比較出誰大誰小了,則不再繼續比下去了

__le__小于等于strA= 'hello'

print(strA.__lt__('ello'))#True

#字符串小于比較與小于等于比較類似,唯一一點是小于比較時,對象與傳入的參數大小寫不能完全一樣

__lt__小于

strA= 'hello'

print(strA.__mul__(3))#hellohellohello

#打印結果將輸出三個hello

__mul__ 乘法運算

__le__小于等于

strA = "hello"

print(strA.__ne__('HEllo'))#True

#字符串不等于運算比較,凡是對象與傳入參數只要有一個字母大小寫不一樣則為真,否則為假

__ne__ 不等于比較

strA = "HELLO"

print(strA.zfill(6))#0HELLO

#當傳入的參數長度比對象長度大時,多余的長度則以0進行填充

zfill 以0填充

strA = "hELlo1112123"

print(strA.upper())#HELLO

#將所有的字母轉換為大寫

upper 字母轉換大寫

print("hello world".title())#Hello World

#每個單詞首字母大寫輸出,且單詞的第二位后面都會變成小寫,如helLO,最終會格式化為Hello

title 標題

print("hEllO".swapcase())#HeLLo

#將原來的大小字母轉換成小寫字母,小寫轉換成大小字母

swapcase 大小寫轉換

print("hello world".strip())#hello world#將字符串兩邊的空格去掉

strip 去除字符串兩邊的空格

print("hello".startswith('h'))#True

print("hello".startswith('h',1))#False

#startswith這個函數可以指定起始位置進行判斷字符是否存在

startswith 字符串是否存在該字符

print("hello\nworld".splitlines())#['hello','world']

#splitlines默認以\n換行符進行分割字符,最終返回一個列表

splitlines 以換行符分割字符串

print("hello world".split())#['hello','world']

print("hello world".split('\n'))#['hello world',]

#默認以空格分割字符串,可以指定分隔符

split 默認以空格分割字符

print("hello world".rstrip())#hello world#打印將會把world后面的空格去除

rstrip 去除右邊的空格

print("hello world".rpartition('he'))#('', 'he', 'llo world ')#只返回傳入參數且存在字符串里的字符然后組合成一個新的元組

rpartition 返回字符串的一部分

print("hello world".rjust(20))#hello world#默認以空格填充,從左到最后一個單詞d結尾一個長度為20,也就是說h前面有9個空格

print("hello world".rjust(20,'+'))#+++++++++hello world#這里以‘+’填充,對比上面,可以看的更具體,前面有9個+被用來填充

rjust 向右偏移

print("hello world".rindex('wo'))#6#通過查找字符串'wo'獲取該字符串在hello world 里面的下標位置,這里從左往右數,第七個位置,字符串的下標默認從0開始,所以返回6#當找不到時則拋出異常

rindex 查找下標

strA = 'hello 123'table1= str.maketrans('123','我很好')print(strA.translate(table1))#hello 我很好

#將字符串里面的123通過table進行翻譯成對應的值,table1的123長度必須和‘我很好長度對應’

strA= 'hello 12'table1= str.maketrans('123','我很好')print(strA.translate(table1))#hello 我很

translate 翻譯

print("hello".rfind('e'))#1

print("hello".rfind('ee'))#-1

如果找到,則結果為對應的下標,否則返回-1

rfind 從左到右查找

print('hello world'.replace('e','o'))#hollo world#將字符串里面所有的e替換成o,區分大小寫

replace 字符串替換

print('hello world'.rpartition('el'))#('h', 'el', 'lo world')#效果與rpartition相似

partition 截取字符串

table1 = str.maketrans('123','我很好')print(table1)#{49: 25105, 50: 24456, 51: 22909}

#首先傳入的必須是兩個參數,且長度相等#返回結果將是一個字典類型,每一個字符串將會映射到第二個參數的相同位置的字符串上,#當這里存在三個參數時,第三個參數必須是一個字符串類型,且整個字符串將被映射成None

strA= 'hello 1233颯颯'table1= str.maketrans('123','我很好','颯颯')print(strA.translate(table1))print(table1)#以下為輸出結果#hello 我很好好#{49: 25105, 50: 24456, 51: 22909, 39122: None}

#這個字典的值將被映射成unicode值,如49表示unicode的1

maketrans 翻譯表

print("hello world".lstrip())#hello world

將hello左邊空格去除

lstrip 去除左邊的空格

print("HELLo22".lower())#hello22#將所有字母轉換為小寫

lower 轉換小寫

print("hello world".ljust(20,'+'))#hello world+++++++++#從右向左開始進行填充,總長度為20

ljust 右填充

print('+'.join(('hello','world')))#hello+world#通過一個字符串去與join里面的一個迭代器里的字符串進行聯結生存一個新的字符串

join 生存一個字符串

print('Hello'.isupper())print('HELLO1'.isupper())#False#True

#判斷所有的字母是否都是大小,是則返回真,否則假

isupper 是否全部大小

print('Hello'.istitle())print('Hello world'.istitle())#True#False#判斷每個單詞首字母是否大寫,是則為真,否則為假

istitle 是否是標題

print('hello'.isspace())print(' '.isspace())#False#True#判斷內容是否為空格

isspace 是否是空格

print('hello world'.isprintable())print('\n'.isprintable())#True#False#由于換行符是特殊字符,不可見,所以不能被打印,結果為假

issprintable 是否可以被打印

print('111'.isnumeric())print('壹'.isnumeric())print('1q'.isnumeric())#True#True#False#True包含unicode數字,全角數字(雙字節),羅馬數字,漢字數字

isnumeric 是否是數字

print('Hello'.islower())print('hello'.islower())#False#True#判斷字母是不是都是小寫,是則為真,否則為假

islower 是否是小寫

print('def'.isidentifier())print('hello'.isidentifier())print('2a2'.isidentifier())#True#True#False

#用來檢測標識符是否可用,也就是說這個名字能不能用來作為變量名,是否符合命名規范,如果符合則為真#通常會結合keyword.iskeyword()這個方法去在做判斷是否是關鍵字,防止因命名不規范導致某些內置功能不可用

isidentifier

print('hello'.isdigit())print('111e'.isdigit())print('壹'.isdigit())print('121'.isdigit())#False#False#False#True

#unicode數字,全角數字(雙字節),byte數字,羅馬數字都為真

isdigit 是否是數字

print('11'.isdecimal())print('壹'.isdecimal())print('11d'.isdecimal())#

#True#False#False#只有全部為unicode數字,全角數字(雙字節),結果才為真

isdecimal 是否是數字

print('hee'.isalpha())print('Hello'.isalpha())print('1212'.isalpha())print('hhee1'.isalpha())#True#True#False#False#當結果都是字母則為真,否則為假

isalpha 是否是字母

print('hew11'.isalnum())print('HHH'.isalnum())print('112'.isalnum())print('q'.isalnum())print('!!@~d'.isalnum())#True#True#True#False#False

#當結果為任意數字或字母時,結果為真,其他字符為假

isalnum 是否為數字或字母

print('hello'.index('e'))print('hello'.index('el'))print('hello'.index('el',1))#1#1#1#通過查找制定的字符獲取對應字符串的下標位置,可以指定起始位置,第3個事咧則表示從下標1開始查找,包括下標1的位置,如果指定end的結束位置,查找是不包括end的位置本身

index 通過字符查找下標

print('hello'.find('h',0))print('hello'.find('h',1))#0#-1

#find是從下標0位置開始找起,包含開始的位置0,如果有結束的位置,不包含結束位置,查找到則顯示具體下標位置,否則顯示-1

find查找字符串下標

print('hello{0}'.format('world'))print('hello{0}{1}'.format('world','python'))print('hello{name}'.format(name='world'))#hello world#hello world python#hello world

format 格式化輸出字符串

print('hello\tworld'.expandtabs(tabsize=8))#hello world 指定制表符長度為8

expandtabs 制表符長度

print('hello'.endswith('lo',3))#True#判斷結束字符是否為lo,默認從下標0開始查找,包含下標0的位置

endswith 判斷結束字符

print('我好'.encode())print('hello'.encode())#print('hela!~@@~!\xe2lo'.encode('gbk',errors='strict'))

print(b'\xe6\x88\x91\xe5\xa5\xbd'.decode('utf-8'))#b'\xe6\x88\x91\xe5\xa5\xbd'#b'hello'#我好

#將字符串進行編碼,最終返回以b開頭的編碼格式

encode 編碼

print('heelloe'.count('e',1,2))#1#表示從開始下標1包括下標1位置查找字符e,結束位置為下標2,不包括結束位置#統計結果為1

count 統計相同的字符

print('aaa'.center(22,'+'))#+++++++++aaa++++++++++#表示將字符aaa的位置顯示在長度為22的中間位置,默認是空格方式填充,這里以+號填充方便演示效果,注意,由于22-3(字符本身3個長度),剩余的并不能整除,所以先整除的整數部分作為公共的填充內容,剩余的填充到末尾

center 中心顯示

print('hDasdd23ellAo'.casefold())#hdasdd23ellao

#將字符串里面所有的字母都轉換為小寫輸出

casefold 字母轉換小寫

print('hEello World'.capitalize())#Heello world#這個方法會將整個字符串的第一個字母大寫,其余都是小寫輸出,如果第一個字符串不是字母,則只將其余字母轉換成小寫

capitalize 首字母大寫

3.list

#定義一個列表

b = ['a','hello','python','1']#查看列表的內置方法

dir(b)#2.x 輸出 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

#3.x輸出['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

b.append('tail') #在列表末尾追加一個元素'tail'

b.count('python') #統計列表中有多少個相同的元素'python'

b.extend('how') #在列表后面追加三個字符串'h','o','w'

b.index('python') #顯示元素‘python’的索引,這里將輸出2

b.insert(1,'niubi') #在索引為的位置插入元素'niubi',及原來的元素從1往后加1

b.pop() #將列表最后一個元素刪除

b.remove('niubi') #刪除指定元素,即,將指定的'niubi'元素刪除

b.reverse() #將列表的元素由原來的從左到右順序變成從右到左方式排序

b.sort() #將列表按照assci🐎順序排序,注意!3.x版本的排序是不能同時有多個數據類型一起排序的。

b.clear() #將列表b清空,這個方法只有3.x才有

a = b.copy() #將列表b復制給a,貌似沒有發現有什么其它特別之處相對于直接使用a = b方式,這個屬性也是只有3.x版本才有

4.tuple

#例如,定義一個元組

a = ('a','hello','python','1')#查看元組的內置方法

dir(a)#將會輸出一個列表形式的方法名稱#2.x 輸出['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

#3.x輸出 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

#元組提供了兩個公有方法給我們使用

a.count('hello') #統計元組里面有多少個相同的元素'hello',很顯然,這里只有1個,所以輸出結果為 1

a.index('hello') #返回元素'hello'的索引位置,python的索引位置是從0開始的,所以這里的‘hello’元素的索引是1,而不是2.

#元組的訪問方式

a[1] #顯示下標為1的元素,因為元組的下標是從0開始的,所以會顯示元素'hello'

a[2] #這里會顯示第python這個元素

a[0:1] #顯示元素從位置0(包括0) 到1(不包括1),即顯示'a'

a[0:2] #顯示元素從位置0(包括0)到2(不包括2),即顯示('a','hello')

a[-1] #顯示倒數第一個元素,即'1'

a[-2] #顯示倒數第二個元素,即'python'

a[:-2] #顯示元素從位置0(包括),到位置倒數第二個(不包括倒數第二個),之前的元素都顯示出來,即('a','hello')

a[-2:] #顯示元素從位置倒數第二個(包括)到最后一個(包括),即('python','1')

a[0:4:2] #該方式先將前面的[0:4]條件先篩選出來,然后再進行后面的:2,即每隔一位取一個值,所以這里將顯示('a','python')

5.dict

#python3.5

dir(dict)#['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

#python2.x

dir(dict)#['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

food = {'1':'apple','2':'banana'}print(food)

food.clear()print(food)#{'2': 'banana', '1': 'apple'} 正常打印結果#{} 調用字典函數clear打印結果

clear 清空字典

food = {'1':'apple','2':'banana'}

newfood=food.copy()print(newfood)#{'1': 'apple', '2': 'banana'} 打印輸出,

copy 淺拷貝字典

food = {'1':'apple','2':'banana'}print(food.fromkeys(('w'),('2','5')))print(food)#{'w': ('2', '5')}#{'2': 'banana', '1': 'apple'}

#注意,這個操作并不會改變字典的數據值,僅僅是返回一個新字典

fromkeys 返回一個新字典

food = {'1':'apple','2':'banana'}print(food.get('22'))print(food.get('1'))print(food.get('22','neworange'))print(food.get('1','neworange'))print(food)#None 如果沒有這個key將返回一個默認值none#apple 如果能能查到key則顯示對應的值#neworange 如果查不到,則顯示默認的值#apple 如果能查到key,只顯示key對應的值,否則使用默認的值#{'1': 'apple', '2': 'banana'} get不會改變字典內容

get 獲取字典值

food = {'1':'apple','2':'banana'}print(food.items())#dict_items([('1', 'apple'), ('2', 'banana')]) 將字典的鍵存放在一個元組,對應的值也放在另一個元組里面,返回

items 獲取字典的key,values

food = {'1':'apple','2':'banana'}print(food.keys())#dict_keys(['2', '1'])

keys 以元組形式返回字典鍵

food = {'1':'apple','2':'banana'}

result= food.pop('1')print(result)print(food)#apple 將被刪除的鍵對應的值返回#{'2': 'banana'} 打印更新后的字典

pop 刪除指定的鍵值對

food = {'1':'apple','2':'banana'}print(food.popitem())print(food)#('1', 'apple') 隨機刪除鍵值對#{'2': 'banana'} 返回刪除后的字典

popitem 隨機刪除鍵值對

food = {'1':'apple','2':'banana'}print(food.setdefault('3','orange'))print(food)#orange 默認的值#{'3': 'orange', '2': 'banana', '1': 'apple'} 打印字典

setdefault 設置默認的鍵值對

food = {'1':'apple','2':'banana'}

goods= {'1':'TV','22':'Computer'}print(food.update(goods))print(food)#None#{'2': 'banana', '1': 'TV', '22': 'Computer'} 如果存在對應的key則更新value,否則新增鍵值對

update 更新字典

food = {'1':'apple','2':'banana'}print(food.values())#dict_values(['apple', 'banana'])

values 以列表形式返回字典的值

6.數據類型轉換

列表轉換成元祖

#定義一個列表

a = ['a', 'b', 'c']#通過tuple函數,將列表轉換成元組,我們把新生成的元組賦值給c

c =tuple(a)print(c)#結果顯示('a', 'b', 'c'),說明我們現在已經把列表轉換成一個新的元組了。

元組轉換成列表

#由于元組上不可更改的,當我們想變更時該怎么辦呢?只能將元組轉換成列表,將其修改后,再轉換成元祖形式#定義一個元組

a = ('a','b','c')#使用list函數將元組轉換成列表,然后賦值給一個新的變量名為c,這樣c就有list函數所有屬性了

c =list(a)print(c)#打印結果輸出為 ['a', 'b', 'c'],通過這種方法,如果我們想在現有的元組基礎上做操作修改,可以先轉換成列表,列表是考驗直接修改元素的,修改完后,我們再將它轉換成元組,重新賦值給a

7.文件處理

7.1文件操作語法

file object = open(file_name,[access_mode],[buffering])

·file_name:file_name參數是一個字符串值,包含要訪問的文件的名稱。

·access_mode:access_mode確定該文件已被打開,即模式。讀、寫等追加,可能值的一個完整 列表在下表中給出。這是可選的參數,默認文件訪問模式是讀(r)

·buffering:如果緩沖值被設置為0,沒有緩沖將發生。如果該緩沖值是1,將在訪問一個文件進行緩沖。如果指定的緩沖值作為大于1的證書,那么緩沖操作將被用指定緩沖器大小進行。這是可選的參數。

7.2文件訪問模式

模式

描述

r

以只讀方式打開文件,文件指針放在文件開頭,這個是默認模式

rb

以二進制格式讀取,文件指針放在文件開頭

r+

以讀取和寫入方式打開文件,文件指針在文件開頭

rb+

以二進制讀取和寫入方式打開文件

w

以只寫方式打開文件,如果文件存在,則覆蓋文件內容,不存在則創建一個新文件

wb

打開文件以二進制方式寫入,文件存在則覆蓋,不存在則創建新文件

w+

以寫入和讀取方式打開文件,如果文件存在則覆蓋,不存在則創建新文件

wb+

以二進制方式寫入和讀取文件,存在則覆蓋現有文件,不存在則創建新文件

a

以追加方式寫入文件末尾,如果不存在則創建該文件

ab

以二進制格式追加在文件末尾,不存在則創建該文件

a+

以追加和讀取方式打開文件,如果文件存在,文件指針在文件的末尾,如果不存在,則創建新文件并寫入和讀取

7.3文件的操作示例

open_file = open('/tmp/file.txt',r+) #以讀取和寫入方式打開文件

open_file.write('hello\n') #寫入內容,加上換行符,

open_file.close()#打開文件后,不做操作需要關閉

#文件操作有以下幾種方法#2.x 方法 ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

#3.x 方法['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

總結

以上是生活随笔為你收集整理的python将元祖设为整形_python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 成人在线免费看视频 | 黄色天堂网 | 精品无码人妻少妇久久久久久 | 免费在线观看的av | 精品国产乱码久久久久久闺蜜 | 日韩免费不卡视频 | 久久人人视频 | 91高跟黑色丝袜呻吟动态图 | 一级真人毛片 | 国产精品国产三级国产专区51 | 高清av网| 麻豆毛片 | 国模无码国产精品视频 | 一区二区三区免费在线观看视频 | 国产一线二线三线在线观看 | 黄视频免费在线观看 | av黄色天堂 | 欧美色图影院 | 日本国产亚洲 | 久久r视频 | va在线视频 | 日韩毛片一区二区三区 | www啪啪| 国产中文字幕在线观看 | 亚洲乱乱 | 欧美老肥妇做.爰bbww视频 | 在线日韩亚洲 | 99国产免费 | 久久不射视频 | av在线资源播放 | 国产999精品视频 | 最新视频 - 88av | 国产粉嫩在线观看 | 日本黄色免费观看 | 亚洲国产婷婷香蕉久久久久久99 | 麻豆av电影在线观看 | 国产女人在线视频 | 日本免费看 | 欧美性猛交xx乱大交 | 精品国产精品网麻豆系列 | 激情久久五月天 | 欧美综合一区 | av在线播放地址 | 高h喷水荡肉少妇爽多p视频 | 日韩性生活视频 | 99热久久这里只有精品 | 四虎国产在线观看 | 欧美日韩国产三级 | 五月天色综合 | 国产精品成人免费精品自在线观看 | 国产视频一区在线播放 | 国产亚洲欧美视频 | 欧美成人乱码一二三四区免费 | 污视频在线播放 | 欧美性xxxxx 亚洲特黄一级片 | 国产欧美一区二区三区在线老狼 | 日韩午夜在线播放 | 激情亚洲 | 中国一极毛片 | 黄色一级免费 | 好吊操av| 久久网免费视频 | 亚洲区小说区 | 中文字幕理伦片免费看 | 亚洲精品国产av | 免费看黄网站在线观看 | 国产夫妻露脸 | 欧美 日韩 国产 一区二区三区 | 日本美女动态 | 久久精品2019中文字幕 | 国产一级淫片免费 | 高清毛片aaaaaaaaa郊外 | 中文字幕一区二区三区门四区五区 | 麻豆疯狂做受xxxx高潮视频 | 在线不卡日本 | 蜜桃av色偷偷av老熟女 | 日韩欧美国产片 | 国产无精乱码一区二区三区 | 毛片毛多水多 | 亚洲高清在线观看 | 调教在线观看 | 国产精品久久久久影院 | 91无限观看| 不卡三区 | 97se在线| 99re在线观看视频 | 欧美高清一区二区三区四区 | 亚洲 日本 欧美 中文幕 | 欧美日韩在线视频免费播放 | 人妻无码一区二区三区免费 | 日韩免费网站 | 九九热视频这里只有精品 | 亚洲自拍成人 | 香港一级淫片免费放 | 亚洲作爱视频 | 3344成人 | 亚洲第一二三四区 | 一级少妇毛片 | 精品国产99久久久久久 |