接上篇Python基础(一)——字符串、列表和元组的常用方法
4 字典
常用的方法:
del:删除字典中指定键
clear:清空整个字典
items:获得字典的项的列表
keys:获得字典的键的列表
values:获得字典的值的列表
setdefault:设置键的默认值
update:更新字典
get:获取键的值,如果键不存在则返回备用值
dictionary={'China':'Beijing','US':'NewYork','UK':'London'}
dictionary.setdefault('Singapore','Singapore')
print(dictionary)
print(dictionary.get('India','Mumbai'))
print([item for item in dictionary.items()])
print([key for key in dictionary.keys()])
print([value for value in dictionary.values()])
dictionary.update({'Russia':'Moscow'})
print(dictionary)
dictionary.clear()
print(dictionary)
{'China': 'Beijing', 'US': 'NewYork', 'UK': 'London', 'Singapore': 'Singapore'}
Mumbai
[('China', 'Beijing'), ('US', 'NewYork'), ('UK', 'London'), ('Singapore', 'Singapore')]
['China', 'US', 'UK', 'Singapore']
['Beijing', 'NewYork', 'London', 'Singapore']
{'China': 'Beijing', 'US': 'NewYork', 'UK': 'London', 'Singapore': 'Singapore', 'Russia': 'Moscow'}
{}
5 集合
集合由于元素的不可重复性经常用来消除列表中的重复元素
常用的方法:
add:添加元素到集合里面
remove:删除集合中指定元素
pop:删除集合里面的一个元素
issubset:判断是否为子集
issuperset:判断是否为超集
test_set={1,2,3,4,5,7,8,9}
set2={4,5}
test_set.add('a')
print(test_set)
test_set.pop()
print(test_set)
test_set.remove(9)
print(test_set)
print(set2.issubset(test_set))
print(test_set.issuperset(set2))
{1, 2, 3, 4, 5, 'a', 7, 8, 9}
{2, 3, 4, 5, 'a', 7, 8, 9}
{2, 3, 4, 5, 'a', 7, 8}
True
True
#集合的运算
# 求交集
print(test_set & set2)
print(test_set.intersection(set2))
# 求并集
print(test_set | set2)
print(test_set.union(set2))
# 求差集(A-A&B)
print(test_set-set2)
print(test_set.difference(set2))
# 对称差(A|B-A&B),也叫异或
print(test_set^set2)
print(test_set.symmetric_difference(set2))
{4, 5}
{4, 5}
{2, 3, 4, 5, 'a', 7, 8}
{2, 3, 4, 5, 'a', 7, 8}
{2, 3, 'a', 7, 8}
{2, 3, 'a', 7, 8}
{2, 3, 'a', 7, 8}
{2, 3, 'a', 7, 8}
6 其他
6.1 使用zip从列表创建字典
list1=['China', 'US', 'UK', 'Singapore']
list2=['Beijing', 'NewYork', 'London', 'Singapore']
new_dictionary=dict(zip(list1,list2))
print(new_dictionary)
{'China': 'Beijing', 'US': 'NewYork', 'UK': 'London', 'Singapore': 'Singapore'}
6.2 sorted函数
list1=[1,13,25,'hello',2233,'234']
# 根据元素长度进行排序
print(sorted(list1,key=lambda i:len(str(i))))
[1, 13, 25, '234', 2233, 'hello']