python - 使用临时变量与从字典中重复读取相同的键/值
问题描述
背景:我需要从字典中(完全)读取相同的键/值两次。
问:有两种方式,如下图,
方法 1. 用同一个键读取两次,例如,
sample_map = {'A':1,}
...
if sample_map.get('A', None) is not None:
print("A's value in map is {}".format(sample_map.get('A')))
方法 2. 读取一次并将其存储在局部变量中,例如,
sample_map = {'A':1,}
...
ret_val = sample.get('A', None)
if ret_val is not None:
print("A's value in map is {}".format(ret_val))
哪种方式更好?他们的优点和缺点是什么?
请注意,我知道print()
可以自然地处理ret_val
. None
这是一个假设示例,我只是将其用于说明目的。
解决方案
在这种情况下,我也不会使用。你真正感兴趣的是是否A
是一个有效的密钥,并且提出的KeyError
(或缺乏的)__getitem__
会告诉你它是否是。
try:
print("A's value in map is {}".format(sample['A'])
except KeyError:
pass
或者当然,有些人会说块中的代码太多try
,在这种情况下方法2会更好。
try:
ret_val = sample['A']
except KeyError:
pass
else:
print("A's value in map is {}".format(ret_val))
或您已有的代码:
ret_val = sample.get('A') # None is the default value for the second argument
if ret_val is not None:
print("A's value in map is {}".format(ret_val))
推荐阅读
- python - 如何在超时的情况下从 GPIO 读取输入
- mysql - MySQL 中的聚合函数 GROUP_CONCAT
- c# - Renci SshNet“服务器响应不包含ssh协议标识”
- visual-studio - 如何将 Azure Analysis Services 项目从只读更改为读写?
- r - 我不知道如何使用 rgl 向 3d 图形添加标题
- javascript - OnClick 钩子调用 - 反应
- python - 如何使用python客户端和C服务器通过套接字正确发送图像
- c# - 表单中的 C# 组合框不添加项目
- r - 对数的底数大于 10 的 ggplot scale_x_log10()
- c++ - 如何将两个从十进制转换的二进制数相加