新聞中心
創(chuàng)新互聯(lián)Python教程:

創(chuàng)新互聯(lián)建站堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計(jì)制作、做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的老河口網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
寫(xiě)一個(gè) Python 程序來(lái)創(chuàng)建鍵的字典,用一個(gè)實(shí)際的例子來(lái)說(shuō)明值是鍵的平方。
創(chuàng)建鍵和值的字典的 Python 程序是鍵的平方示例 1
在這個(gè) python 程序中,我們使用 for 循環(huán)從 1 迭代到用戶指定的值。在 Python for 循環(huán)中,我們使用指數(shù)運(yùn)算符為字典賦值。
# Python Program to Create Dictionary of keys and values are square of keys
number = int(input("Please enter the Maximum Number : "))
myDict = {}
for x in range(1, number + 1):
myDict[x] = x ** 2
print("\nDictionary = ", myDict)
在這個(gè) Python 的例子中,number = 5。
第一次迭代 x 將是 1:1,范圍為(1,6) myDict[x]= x 2 myDict[x]= 1 2 = 1
第二次迭代 x 將是 2:對(duì)于范圍(1,6) 中的 2,my dict[x]= 2 2 = 2
對(duì)循環(huán)迭代的剩余進(jìn)行同樣的操作
創(chuàng)建從 1 到 n 的鍵的字典的程序,值是鍵的平方示例 2
這個(gè) python 代碼創(chuàng)建鍵和值的字典是鍵的平方是另一種方法。
# Python Program to Create Dictionary of keys and values are square of keys
number = int(input("Please enter the Maximum Number : "))
myDict = {x:x ** 2 for x in range(1, number + 1)}
print("\nDictionary = ", myDict)將鍵字典和鍵方塊輸出為值
Please enter the Maximum Number : 6
Dictionary = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
>>>
Please enter the Maximum Number : 9
Dictionary = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> 網(wǎng)站欄目:Python程序:創(chuàng)建值是鍵的平方的字典
文章源于:http://m.fisionsoft.com.cn/article/djgspcc.html


咨詢
建站咨詢
