标签:tde xixi pop 打印 update hang python基础 beijing from
元组:以一对小括号表示,不可以增删改,只可查看。
字典:以一对大括号表示,字典中含key及value,字典是无序的。
下面介绍字典和元组的一些常见操作:
一、元组
a = (‘haha‘,‘xixi‘,‘lala‘,‘haha‘)
print(a.count(‘haha‘)) ##统计a元组中haha元素的个数
print(a.index(‘xixi‘)) ##显示xixi元素的下标
del a ##删除元组a
结果:
2
1
二、字典
dict_a = {‘beijing‘:‘haidian‘,‘shanghai‘:‘zhabei‘,‘shenzhen‘:‘futian‘}
print(dict_a.keys()) ##打印字典中所有的key
print(dict_a.values()) ##打印字典中所有的value
print(dict_a.get(‘beijing‘)) ##判断字典中是否有beijing这个key,该方法只能判断字典中是否有key
print(dict_a.get(‘haidian‘))
dict_a.pop(‘shanghai‘) ##删除字典中名字叫作shanghai的key
print(dict_a)
del dict_a[‘beijing‘] ##删除字典中名字叫作beijing的key
print(dict_a)
dict_a.setdefault(‘guangzhou‘,‘tianhe‘) ##向字典中添加key及对应的value
print(dict_a)
dict_b = {1:‘well‘,2:‘goog‘,3:‘better‘}
dict_a.update(dict_b) ##将字典b加到字典a中
print(dict_a)
print(dict_a.items()) ##将字典转换为列表
dict_c = dict.fromkeys([4,5,6],‘test‘) ##初始化一个字典,4,5,6为key,test为value
print(dict_c)
结果:
dict_keys([‘beijing‘, ‘shenzhen‘, ‘shanghai‘])
dict_values([‘haidian‘, ‘futian‘, ‘zhabei‘])
haidian
None
{‘beijing‘: ‘haidian‘, ‘shenzhen‘: ‘futian‘}
{‘shenzhen‘: ‘futian‘}
{‘shenzhen‘: ‘futian‘, ‘guangzhou‘: ‘tianhe‘}
{‘guangzhou‘: ‘tianhe‘, 2: ‘goog‘, 3: ‘better‘, 1: ‘well‘, ‘shenzhen‘: ‘futian‘}
dict_items([(‘guangzhou‘, ‘tianhe‘), (2, ‘goog‘), (3, ‘better‘), (1, ‘well‘), (‘shenzhen‘, ‘futian‘)])
{4: ‘test‘, 5: ‘test‘, 6: ‘test‘}
标签:tde xixi pop 打印 update hang python基础 beijing from
原文地址:http://www.cnblogs.com/xiaoyu866/p/6250711.html