字典推导式
字典推导式语法和列表推导式语法类似:
my_dict = { expr for value in collection if condition }
我们下面将两个列表转换成一个字典:
keys = ['a', 'b', 'c', 'd'] vals = [10, 20, 30, 40] my_dict = {key: value for key, value in zip(keys, vals)} print(my_dict)
例子1:
# 01: # 准备两个列表 keys = ["a", "b", "c", "d"] values = [1, 3, 5, 7] # 定义一个字典(空字典) my_dict = {} # 循环 for i, key in enumerate(keys): # 添加元素 my_dict[key] = values[i] print(my_dict)
运行结果:
{'a': 1, 'b': 3, 'c': 5, 'd': 7}
例子2:
import sys # 02: zip函数 a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] # 计算a b c 分别占用了多少内存空间 # 占用88字节 # 1024字节 = 1kb print(sys.getsizeof(a)) print(sys.getsizeof(b)) print(sys.getsizeof(c))
运行结果:
88 88 88
例子3:
import sys # 02: zip函数 a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] # 计算a b c 分别占用了多少内存空间 # 占用88字节 # 1024字节 = 1kb # print(sys.getsizeof(a)) # print(sys.getsizeof(b)) # print(sys.getsizeof(c)) # 压缩 my_zip = zip(a, b, c) print(sys.getsizeof(my_zip)) print(list(my_zip))
运行结果:
64
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
例子4:
import sys # 02: zip函数 a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] # 计算a b c 分别占用了多少内存空间 # 占用88字节 # 1024字节 = 1kb # print(sys.getsizeof(a)) # print(sys.getsizeof(b)) # print(sys.getsizeof(c)) # 压缩 my_zip = zip(a, b, c) # print(sys.getsizeof(my_zip)) # print(list(my_zip)) # # 解压缩 a1, b1, c1 = zip(*my_zip) print(a1) print(b1) print(c1)
运行结果:
(1, 2, 3) (4, 5, 6) (7, 8, 9)
例子5:
# 03: 字典推导式 # 准备两个列表 keys = ["a", "b", "c", "d"] values = [1, 3, 5, 7] # my_zip = zip(keys, values) # print(list(my_zip)) my_dict = {k:v for k, v in zip(keys, values)} print(my_dict)
运行结果:
{'a': 1, 'c': 5, 'b': 3, 'd': 7}
例子6:
import sys # 04: # 列表推导式 my_list = [i for i in range(10000)] print(sys.getsizeof(my_list)) # 生成器 g = (i for i in range(10000)) print(type(g)) print(sys.getsizeof(g))
运行结果:
87624 <class 'generator'> 88