python字典及集合
时间:2021-04-13 10:40:32
收藏:0
阅读:44
1.字典的构造
items = [(‘name‘, ‘Gumby‘), (‘age‘, 42)] #用列表构建字典 d = dict(items) print(d) d = dict(name=‘Gumby‘, age=42, height=1.76) #函数形式构建字典 print(d)
在python3.5及以前字典是无序的,以后是按加入字典的顺序排序的
2.字典的拷贝(浅拷贝)
x = {‘username‘: ‘admin‘, 1978: [1, 2, 3]} y = x.copy() # 浅拷贝,深拷贝用copy.deepcopy() y[‘username‘] = ‘mlh‘ y[1978].remove(2) # 因为浅拷贝,只是拷贝了指针。他们实际指向的是同一个列表。所以一修改y,x也会变化 print(y) # {‘username‘: ‘mlh‘, 1978: [1, 3]} print(x) # {‘username‘: ‘admin‘, 1978: [1, 3]}
3.字典的深拷贝
import copy x = {‘username‘: ‘admin‘, ‘machines‘: [‘foo‘, ‘baz‘, ‘bar‘]} y = copy.deepcopy(x) y[‘username‘] = ‘mlh‘ y[‘machines‘].remove(‘bar‘) # 字典的深拷贝,所以不论y如何变化都不会影响x print(y) # {‘username‘: ‘mlh‘, ‘machines‘: [‘foo‘, ‘baz‘]} print(x) # {‘username‘: ‘admin‘, ‘machines‘: [‘foo‘, ‘baz‘, ‘bar‘]}
4.集合的构造(不可变类型才可以作为集合的元素,可变类型无法作为集合的元素)
集合的作用是快速判断某个元素是否在一堆东西中
print(set([])) # 用列表构建集合 a = {1, 2, 2, "ok", (1, 3)} print(a) # {‘ok‘, 1, 2, (1, 3)} 集合会自动去重复 b = (3, 4) c = (3, 4) a = set((1, 2, "ok", 2, b, c)) # 用元组构建集合 for x in a: print(x, end=",") # ok,1,2,(3, 4), a = set(‘abc‘) print(a) # 用字符串构建集合 a = set({1: 2, ‘ok‘: 3, (3, 4): 4}) # 用列表构建集合(只会取键) print(a) print(a[2]) # 会报错,字典是无序的
原文:https://www.cnblogs.com/lichengmin/p/14650961.html
评论(0)