5、python入門 元組(Tuples)&字典(Dictionaries) ——Mosh

一、元組,()

元組是不可變的,不能刪除,不能修改,不能增加

訪問元組中的值

1、使用下標索引來訪問元組中單個的值

2、使用連續賦值

上下兩段代碼體現的是一樣的效果,但明顯下面的連續幅值比較簡潔

coordinates = (1, 2, 3)
x = coordinates[0]
y = coordinates[1]
z = coordinates[2]
print(x, y, z)
>>>1 2 3

a, b, c = coordinates
print(a, b, c)
>>>1 2 3

ps:該用法同樣適用於列表

二、字典,{ key1: value1, key2: value2 }

字典與列表一樣,都是可變類型的數據結構。

以鍵值對的形式存在

每個鍵必須是唯一的(類比函數的映射關係)

值可以是單個值(一個字符串、一個數字、一個布爾值),也可以是多個值構成的列表,元組或字典

dic = {'name': 'Jan_zcn', 'age': 21, 'is_girl': True,
        'parents':{'father':'B','mother':'D'},
        'interest':['music','books','running']}
print(dic['age'])
print(dic['parents']['father'])
print(dic['interest'][1])

>>>
21
B
books

訪問字典

1、dictionaries[key]

dictionaries = {'name': 'Jan_zcn', 'age': 21, 'is_verified': True}
print(dictionaries['name'])
>>>Jan_zcn

用這種方法的話,假設在訪問過程中輸入了錯誤的鍵key(比如:大小寫錯誤或拼寫錯誤或想訪問根本不存在的鍵值),則會有錯誤(keyerror)

2、dictionaries.get(key)

dictionaries = {'name': 'Jan_zcn', 'age': 21, 'is_verified': True}
print(dictionaries.get('name'))
>>>Jan_zcn

用這種方法假設在訪問過程中輸入了錯誤的鍵(key),則會返回‘None

dictionaries = {'name': 'Jan_zcn', 'age': 21, 'is_verified': True}
print(dictionaries.get('birthday'))
>>>None
dictionaries.get(key, default)

可以設置默認值,當字典中沒有該鍵值時輸出默認值

dictionaries = {'name': 'Jan_zcn', 'age': 21, 'is_verified': True}
print(dictionaries.get('birthday', 'July 21 1998'))

3、dictionaries.keys(),values()和items()

dictionaries.keys() #取出字典中的所有
dictionaries.values() #取出字典中的所有
dictionaries.items() #取出字典中的所有鍵值對

修改字典

1、修改原有鍵的值

語法:dictionaries[key] = new_value

2、新增鍵值對

語法:dictionaries[new_key] = value

3、dictionaries.setdefault(key , value)

此處需要注意一點,不是(key : value)

4、dictionaries.update({‘key’ : ‘valve’})

此處需要注意一點,是({‘key’ : ‘value’})

刪除字典

可以使用pop,poptiem和clear三種方法實現

.pop(‘key’) or[ ].pop()

dictionaries.pop('age')          #刪除年齡信息
dictionaries['parents'].pop('father')   #刪除字典中父親的姓名

.popitem()

dictionaries.popitem() #刪除字典的最後一個元素

.clear()

dict1.clear() #清除字典全部元素

exercise1

phone = input('Phone: ')
dictionaries = {'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
                '5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'}
for number in phone:
    print(dictionaries[number], end = ' ')

>>>
Phone: 123
One Two Three

print(dictionaries[number], end = ’ ')輸出不換行,以空格隔開
end = ''輸出不換行,直接相連,沒有空格隔開

phone = input('Phone: ')
dictionaries = {'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
                '5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'}
output = ''
for ch in phone:
    output += dictionaries.get(ch, '!') + ' '
print(output)

>>>
Phone: 123
One Two Three

對比上面兩段代碼,實現的是同樣的功能,但是第二種容錯率較高,假設用戶輸入了非數值類型,仍能正常輸出而不會有錯誤提示

還有一個exercise,但是隻有mac電腦支持表情輸入的功能,win不支持,我也很無奈

split()

split() 通過指定分隔符對字符串進行切片,如果參數 num 有指定值,則分隔 num+1 個子字符串,並返回分割後的字符串列表

str.split(str="", num)[n]

str – 分隔符,默認爲所有的空字符,包括空格、換行(\n)、製表符(\t)等
[n] – 表示選取第n個分片

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );       # 以空格爲分隔符,包含 \n
print str.split(' ', 1 ); # 以空格爲分隔符,分隔成兩個

>>>['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
>>>['Line1-abcdef', '\nLine2-abc \nLine4-abcd']


txt = "Google#Runoob#Taobao#Facebook"
x = txt.split("#", 1)# 第二個參數爲 1,返回兩個參數列表
print x

>>>['Google', 'Runoob#Taobao#Facebook']

把分割後的字符串保存到變量中

txt = "Google#Runoob#Taobao#Facebook"
a,b,c,d = txt.split("#")# 第二個參數爲 1,返回兩個參數列表
print (a,b,c,d)

Google Runoob Taobao Facebook

多次分隔,獲取需要的結果:

message = 'https://editor.csdn.net/'
print(message.split("//")[1].split("/")[0].split("."))

['editor', 'csdn', 'net']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章