字典#
字典是保存键值对的数据结构,写作 key:value。
另请参阅
你可以这样定义字典:
german_english_dictionary = {'Vorlesung':'Lecture', 'Gleichung':'Equation'}
为了方便读者,可以考虑这样写:
german_english_dictionary = {
'Vorlesung':'Lecture',
'Gleichung':'Equation'
}
german_english_dictionary
{'Vorlesung': 'Lecture', 'Gleichung': 'Equation'}
如果你想访问字典中的特定条目,可以使用方括号和键来访问它:
german_english_dictionary['Vorlesung']
'Lecture'
你可以向字典添加元素:
german_english_dictionary['Tag'] = 'Day'
german_english_dictionary
{'Vorlesung': 'Lecture', 'Gleichung': 'Equation', 'Tag': 'Day'}
你还可以获取字典中所有键的列表:
keys = list(german_english_dictionary.keys())
keys
['Vorlesung', 'Gleichung', 'Tag']
keys[1]
'Gleichung'
表格#
表格可以表示为以数组为元素的字典。
measurements_week = {
'Monday': [2.3, 3.1, 5.6],
'Tuesday': [1.8, 7.0, 4.3],
'Wednesday':[4.5, 1.5, 3.2],
'Thursday': [1.9, 2.0, 6.4],
'Friday': [4.4, 2.3, 5.4]
}
measurements_week
{'Monday': [2.3, 3.1, 5.6],
'Tuesday': [1.8, 7.0, 4.3],
'Wednesday': [4.5, 1.5, 3.2],
'Thursday': [1.9, 2.0, 6.4],
'Friday': [4.4, 2.3, 5.4]}
measurements_week['Monday']
[2.3, 3.1, 5.6]
你也可以在这样的_表格_中存储变量:
w1 = 5
h1 = 3
area1 = w1 * h1
w2 = 2
h2 = 4
area2 = w2 * h2
rectangles = {
"width": [w1, w2],
"height": [h1, h2],
"area": [area1, area2]
}
rectangles
{'width': [5, 2], 'height': [3, 4], 'area': [15, 8]}
练习#
你刚刚测量了三个圆的半径。将它们写入一个表格,并添加一列相应的圆面积测量值。
r1 = 12
r2 = 8
r3 = 15