dict和zip结合使用
zip()函数
函数说明:
zip()可以将两个可迭代对象中的对应元素打包成一个个元组,然后返回这些元组组成的列表
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表
示例:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
dict()函数
函数说明:
dict()创建字典,可以传入元组列表创建字典,也可以通过zip得到元组列表后来创建字典
示例:
>>> dict() # 创建空字典
{}
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
通过zip得到元组列表后来创建字典:
d = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
print(d) # {'three': 3, 'two': 2, 'one': 1}
class_names = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
class_names_to_ids = dict(zip(class_names, range(len(class_names))))
print(class_names_to_ids) # {'daisy': 0, 'dandelion': 1, 'roses': 2, 'sunflowers': 3, 'tulips': 4}