寫一個 Python 程序,用一個實例創建(x,x*x)形式的 1 到 n 的數字字典。
創建(x,x*x)形式的 1 到 n 的數字字典的 Python 程序示例 1
在這個 python 程序中,我們使用 for 循環從 1 迭代到用戶指定的值。在 Python for 循環中,我們使用*運算符為字典賦值。
# 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 程序中,給定數= 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
對循環迭代的剩餘進行同樣的操作
Python 程序以(x,x*x)的形式生成 1 到 n 的數字字典示例 2
這是 Python 創建字典的另一種方法。這裡我們用單行生成 x,xx 形式的數字的字典,請參考 [算術運算符](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}
>>>
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/128536.html