2012-11-18 23 views
-3
tmp = dict(zip(listToAppend, x_test)) 
# x_test is a data vector imported earlier from a file 

回答

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

舉一個two列表並理解它的例子。

zip結合了兩個列表,並創建了一個list2-elements tuple,其中包含兩個列表中的元素。

然後dict轉換是的tuplelist的字典,每個元組爲key和第2個數值作爲價值1st element

>>> 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} 
>>> 

如果您在使用zip結合3 lists,你會得到一個list of 3-elements tuple

另外,如果您的列表大小不一樣,那麼zip只考慮最小大小,並忽略大列表中的額外元素。

>>> l1 = ['a', 'b'] 
>>> l2 = [1, 2, 3] 
>>> zip(l1, l2) 
[('a', 1), ('b', 2)]