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

中江ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!
寫一個 Python 程序,用一個實例創(chuàng)建(x,x*x)形式的 1 到 n 的數(shù)字字典。
創(chuàng)建(x,x*x)形式的 1 到 n 的數(shù)字字典的 Python 程序示例 1
在這個 python 程序中,我們使用 for 循環(huán)從 1 迭代到用戶指定的值。在 Python for 循環(huán)中,我們使用*運算符為字典賦值。
# Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form
number = int(input("Please enter the Maximum Number : "))
myDict = {}
for x in range(1, number + 1):
myDict[x] = x * x
print("\nDictionary = ", myDict)在本 python 程序中,給定數(shù)= 5。
第一次迭代 x 將是 1:1,范圍為(1,6) myDict[x]= x x myDict[1]= 1 1 = 1
第二次迭代 x 將是 2:對于范圍(1,6) 中的 2,myDict[2] = 2 * 2 = 4
對循環(huán)迭代的剩余進行同樣的操作
Python 程序以(x,x*x)的形式生成 1 到 n 的數(shù)字字典示例 2
這是 Python 創(chuàng)建字典的另一種方法。這里我們用單行生成 x,xx 形式的數(shù)字的字典,請參考 [算術(shù)運算符](https://www.tutorialgateway.org/python-arithmetic-operators/)。
# Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form
number = int(input("Please enter the Maximum Number : "))
myDict = {x:x * x for x in range(1, number + 1)}
print("\nDictionary = ", myDict)在為 x 生成字典,x* x 輸出
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}
>>> 分享題目:Python程序:創(chuàng)建(x,x*x)形式的1到n的數(shù)字字典
文章起源:http://m.fisionsoft.com.cn/article/cosicid.html


咨詢
建站咨詢
