本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明
部分答案依旧参考原博主https://blog.csdn.net/xufive/article/details/102993541题库也来自于https://blog.csdn.net/xufive/article/details/102993538写着标准答案的批注是觉得原作者的答案很不错很值得参考
#####################
### 11th,December,2019
### Writed by XingFu
####################
### 21 以列表形式返回字典{'Alice':20, 'Beth':18, 'Ceil':21}中所有的键值对组成的元组
key_value = {'Alice':20, 'Beth':18, 'Ceil':21}
print(key_value.items())
### 标准答案:
### >>> d = {'Alice': 20, 'Beth': 18, 'Cecil': 21}
###>>> [key for key in d.items()] # d.items()返回的类型是,不能使用索引
### 22 向字典{'Alice':20, 'Beth':18, 'Ceil':21}追加'David':19键值对,更新Ceil的值为17
k_v = {'Alice':20, 'Beth':18, 'Ceil':21}
## 更新
k_v['Ceil'] = 17
## 追加
k_v.update({'David':19})
print(k_v)
### 23 删除字典{'Alice':20, 'Beth':18, 'Ceil':21}中的'Beth'键后,清空字典
k_va = {'Alice':20, 'Beth':18, 'Ceil':21}
## 删除
pop_obj = k_va.pop('Ceil')
## 清空
del k_va['Beth'] ### k_va.clear()
# k_va.clear()
# del k_va ## 似乎del 和clear 的方法是不太一样的,用clear()方法是清空字典返回空字典,然而用del方法是直接无返回值
# print(k_va)
### 24 判断"David"和"Alice"是否在字典中
## 方法1:
ke_va = {'Alice':20, 'Beth':18, 'Ceil':21}
ans1 = ['T' if 'David'in ke_va else 'F']
print(ans1)
ans2 = ['T' if 'Alice' in ke_va else 'F']
print(ans2)
## 方法2:
print('David' in ke_va)
print('Alice' in ke_va)
### 25 遍历字典,打印键值对
key_va = {'Alice':20, 'Beth':18, 'Ceil':21}
for k in key_va.keys():
print(k,key_va[k])
### 标准答案:
for key in key_va:
print(key,key_va[key])
### 26 若 a = dict(),令 b = a,执行 b.update({'x':1}), a也被改变为何,如何避免?
a = dict()
# b = a
# b.update({'x':1})
# print('a',a) ### outcome a {'x': 1}
# print('b',b) ### outcome b {'x': 1} 原因: 对象a 和对象b 在内存中是同一个,所以会出现关联
b = a.copy()
b.update({'x':1})
print('a',a) ### outcome a {}
print('b',b) ### outcome b {'x': 1}
### 27 以列表['A','B','C','D','E','F','G','H']中的每一个元素为键,默认值都是0,创建一个字典
lst0 = ['A','B','C','D','E','F','G','H']
lst1 = [0,0,0,0,0,0,0,0]
dict_0 = dict(zip(lst0, lst1))
print("dict_0",dict_0)
### Nice 的标准答案:
dict_ans = dict.fromkeys(['A','B','C','D','E','F','G','H'], 0)
print("dict_ans",dict_ans)
### 28 将二维结构[['a',1],['b',2]]和(('x',3),('y',4))转成字典
h = [['a',1],['b',2]]
s = (('x',3),('y',4))
h1 = dict(h)
s1 = dict(s)
print("h",h1)
print("s",s1)
### 29 将元组(1,2),(3,4)合并成一个元组
y1 = (1,2)
y2 = (3,4)
print("y3",y1+y2)
### 30 将空间坐标元组(1,2,3)的三个元素解包对应到变量x,y,z
### 标准答案:
x,y,z = (1,2,3)
print(x)
print(y)
print(z)