新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Python程序:將兩個(gè)列表映射到一個(gè)字典中
創(chuàng)新互聯(lián)Python教程:

成都創(chuàng)新互聯(lián)是工信部頒發(fā)資質(zhì)IDC服務(wù)器商,為用戶提供優(yōu)質(zhì)的川西大數(shù)據(jù)中心服務(wù)
寫一個(gè) Python 程序,用一個(gè)實(shí)例將兩個(gè)列表映射成一個(gè)字典。
將兩個(gè)列表映射到字典中的 Python 程序示例 1
在這個(gè) python 程序中,我們使用進(jìn)行循環(huán),并帶有 zip 功能。
# Python Program to Map two lists into a Dictionary
keys = ['name', 'age', 'job']
values = ['John', 25, 'Developer']
myDict = {k: v for k, v in zip(keys, values)}
print("Dictionary Items : ", myDict)
將兩個(gè)列表插入字典的 Python 程序示例 2
這段 Python 代碼是將列表插入字典的另一種方法。在這個(gè)程序中,我們使用了 dict 關(guān)鍵字和 zip 函數(shù)。
keys = ['name', 'age', 'job']
values = ['John', 25, 'Developer']
myDict = dict(zip(keys, values))
print("Dictionary Items : ", myDict)
Python 將兩個(gè)列表映射到字典輸出中
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
>>>
將兩個(gè)列表映射到字典中的程序示例 3
這個(gè) Python 將兩個(gè)列表映射到一個(gè)字典中的代碼與上面相同。然而,在這個(gè) python 程序中,我們?cè)试S用戶插入鍵和值。
keys = []
values = []
num = int(input("Please enter the Number of elements for this Dictionary : "))
print("Integer Values for Keys")
for i in range(0, num):
x = int(input("Enter Key " + str(i + 1) + " = "))
keys.append(x)
print("Integer Values for Values")
for i in range(0, num):
x = int(input("Enter Value " + str(i + 1) + " = "))
values.append(x)
myDict = dict(zip(keys, values))
print("Dictionary Items : ", myDict)
Please enter the Number of elements for this Dictionary : 3
Integer Values for Keys
Enter Key 1 = 2
Enter Key 2 = 4
Enter Key 3 = 6
Integer Values for Values
Enter Value 1 = 50
Enter Value 2 = 100
Enter Value 3 = 150
Dictionary Items : {2: 50, 4: 100, 6: 150} 網(wǎng)頁(yè)標(biāo)題:Python程序:將兩個(gè)列表映射到一個(gè)字典中
當(dāng)前地址:http://www.5511xx.com/article/dpjhgde.html


咨詢
建站咨詢
