程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python method of merging two lists into one Dict

編輯:Python

python Put two list Merge into one dict Methods

Don't use built-in functions , Direct use

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]; This method can also '
dit={
list2[i]:list3[i]};
dict.update(dit);
i+=1;
return dict;
if __name__ == '__main__':
print Run();

Use built-in functions zip

1. The two lists have the same length

l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9]
print(dict(zip(l1,l2)))
# result : {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}

2. The length of the two lists is inconsistent ( The principle of obedience to the minority )

l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9,10,11,12]
# First, let ls2 and ls1 Equal length , And then again zip
l3=l2[0:len(l1)]
#print(l3)
print(dict(zip(l1,l3)))
# result : {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}

To simplify the ;

ls1=[1,2,3,4,5,6,7]
ls2=[4,5,8,9,1]
print(dict(zip(ls1,ls2)))
# result :{1: 4, 2: 5, 3: 8, 4: 9, 5: 1}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved