以下Python代码有什么作用?

时间:2012-11-18 17:55:55

标签: python

tmp = dict(zip(listToAppend, x_test))
# x_test is a data vector imported earlier from a file

2 个答案:

答案 0 :(得分:2)

>>> listToAppend = ['a', 'b', 'c']
>>> x_test = [1, 2, 3]
>>> zip(listToAppend, x_test)
[('a', 1), ('b', 2), ('c', 3)]
>>> dict(zip(listToAppend, x_test))
{'a': 1, 'c': 3, 'b': 2}

答案 1 :(得分:1)

two列表为例,了解它。

zip合并了两个列表,并使用两个列表中的元素创建list 2-elements tupledict

然后listtuple 1st element转换为字典,每个元组的key>>> l1 = [1, 2, 3] >>> l2 = [4, 5, 6] >>> zip(l1, l2) [(1, 4), (2, 5), (3, 6)] >>> dict(zip(l1, l2)) {1: 4, 2: 5, 3: 6} >>> ,第二个值为值。

3 lists

如果您使用zip合并list of 3-elements tuple,则会获得zip

此外,如果您的列表大小不同,则>>> l1 = ['a', 'b'] >>> l2 = [1, 2, 3] >>> zip(l1, l2) [('a', 1), ('b', 2)] 仅考虑最小尺寸,并忽略较大列表中的额外元素。

{{1}}
相关问题