寫一個 Python 程序來創建鍵的字典,用一個實際的例子來說明值是鍵的平方。
創建鍵和值的字典的 Python 程序是鍵的平方示例 1
在這個 python 程序中,我們使用 for 循環從 1 迭代到用戶指定的值。在 Python for 循環中,我們使用指數運算符為字典賦值。
# 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)
在這個 Python 的例子中,number = 5。
第一次迭代 x 將是 1:1,範圍為(1,6)
myDict[x]= x 2
myDict[x]= 1 2 = 1
第二次迭代 x 將是 2:對於範圍(1,6)
中的 2,my dict[x]= 2 2 = 2
對循環迭代的剩餘進行同樣的操作
創建從 1 到 n 的鍵的字典的程序,值是鍵的平方示例 2
這個 python 代碼創建鍵和值的字典是鍵的平方是另一種方法。
# 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}
>>>
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241923.html