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']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章