python將兩個list合並成一個dict的方法
不使用內置函數,直接用
def Run():
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d","e"];
dict={
};
i=0;
length=len(list2);
while i<length:
'dict[list2[i]]=list3[i];這種方法也可以'
dit={
list2[i]:list3[i]};
dict.update(dit);
i+=1;
return dict;
if __name__ == '__main__':
print Run();
使用內置函數zip
1.兩個列表的長度一致
l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9]
print(dict(zip(l1,l2)))
#結果: {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}
2.兩個列表的長度不一致(服從少數原則)
l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9,10,11,12]
#先讓ls2和ls1等長,然後再zip
l3=l2[0:len(l1)]
#print(l3)
print(dict(zip(l1,l3)))
#結果: {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}
簡化一下;
ls1=[1,2,3,4,5,6,7]
ls2=[4,5,8,9,1]
print(dict(zip(ls1,ls2)))
#結果:{1: 4, 2: 5, 3: 8, 4: 9, 5: 1}