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的方法:
>>> 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}那么还有一种情况,当两个list的长度不一样,如果要组成dict的话,怎么办呢?
我们直接执行这个就可以,它会自动的匹配!自动的省去多余的部分!
>>> ls1=[1,2,3,4,5,6,7]
>>> ls2=[4,5,89,1]>>> print(dict(zip(ls1,ls2))){1: 4, 2: 5, 3: 89, 4: 1}
浙公网安备 33010602011771号