用 Python 編寫生成以 (x,x*x) 形式包含數字(在 1 到 n 之間)字典的程式。
在需要生成包含給定範圍內的數字且採用特定形式的字典時,會從使用者處獲取輸入資訊,並使用一個簡單的“for”迴圈。
示例
下面對此進行演示——
my_num = int(input("Enter a number.. "))
my_dict = dict()
for elem in range(1,my_num+1):
my_dict[elem] = elem*elem
print("The generated elements of the dictionary are : ")
print(my_dict)輸出
Enter a number.. 7
The generated elements of the dictionary are :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}說明
- 將數字作為使用者輸入資訊。
- 建立一個空字典。
- 遍歷數字。
- 將該數字的平方儲存在字典中。
- 在控制檯上以輸出的形式顯示它。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP