的兩個列表添加到值在字典中我有一個看起來像這樣四個列表:不同長度
lista = [['l', 'k'],['e', '3'],['c', 'k'],['x', 'i'],['d', 'f']]
listanum = [1,2,3,4,5]
listb = [['a', 'k'],['c', 'm'],['v', 'f']]
listbnum = [1,3,4]
lista
和listanum
是同步的,listb
和listbnum
了。 我想要一本字典,其中鍵是listanum
項目和值在lista
和listb
項目,其結果將是:
di = {1: [['l','k'],['a', 'k']],
2: [['e', '3'],[]],
3:[['c','k'],['c', 'm']],
4: [['x', 'i'],['v', 'f']],
5: [['d', 'f'][]]
}
所以如果在數組listB listanum爲一些沒有價值,dictionarys值中的第二個列表是空的。
我已經試過這樣:
di = {}
for i in xrange(len(lista)):
pos = listanum[i]
if pos not in di:
di[pos] = [[],[]]
di[pos][0].append(lista[i])
if i in listbnum:
di[pos][1].append(listb[i])
但收到此錯誤信息:'IndexError: list index out of range'
。我不明白爲什麼它超出範圍?
會不會有一個「+」而不是一個鏈? (在這種情況下) –
@JoranBeasley只在2.x –
@JoranBeasley:不,如果這是Python 3. –