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

2 回答 2

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}
于 2012-11-18T17:57:53.620 回答
1

以列表为例two并理解它。

zip组合这两个列表,并使用两个列表中的元素创建一个listof 。2-elements tuple

然后dict将其转换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 listsusing zip,你会得到一个list of 3-elements tuple.

此外,如果您的列表大小不同,则zip仅考虑最小大小,并忽略较大列表中的额外元素。

>>> l1 = ['a', 'b']
>>> l2 = [1, 2, 3]
>>> zip(l1, l2)
[('a', 1), ('b', 2)]
于 2012-11-18T17:58:37.917 回答