编写一个 Python 程序,以 (x, x*x) 的形式创建从 1 到 n 的数字字典,并附带实际示例。
Python 程序,以 (x, x*x) 形式创建从 1 到 n 的数字字典 示例
在此 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:for 1 in range(1, 6)
myDict[x] = x * x
myDict[1] = 1 * 1 = 1
第二次迭代 x 将是 2:for 2 in range(1, 6)
myDict[2] = 2 * 2 = 4
对于其余的 for 循环迭代,也做同样的事情。
Python 程序,以 (x, x*x) 的形式生成从 1 到 n 的数字字典 示例 2
这是另一种创建字典的 Python 方法。在这里,我们使用单行代码生成 x, x*x 形式的数字 字典。请参阅 * 算术运算符。
# 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}
>>>