如何将两个列表组合生成字典?
1)源码
# how to convert list into dict
list1 = [1, 2, 3] # list1
print(list1)
list2 = ["one", "two", "three"] # list2
print(list2)
obj_zip = zip(list1, list2) # zip object
print("the type of obj_zip is", type(obj_zip))
dic = dict(obj_zip) # convert zip object to dict
print(dic)
2)执行结果
3)zip函数说明
- zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。 - zip() 函数在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象