-3
tmp = dict(zip(listToAppend, x_test))
# x_test is a data vector imported earlier from a file
tmp = dict(zip(listToAppend, x_test))
# x_test is a data vector imported earlier from a file
>>> 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}
舉一個two
列表並理解它的例子。
zip
結合了兩個列表,並創建了一個list
的2-elements tuple
,其中包含兩個列表中的元素。
然後dict
轉換是的tuple
list
的字典,每個元組爲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)]