偶尔使用字典替换值时,
.get(x, x)
和.get(x) or x
等价吗?
例如:
def current_brand(brand_name):
rebrands = {
"Marathon": "Snickers",
"Opal Fruits": "Starburst",
"Jif": "Cif",
"Thomson": "TUI",
}
return rebrands.get(brand_name, brand_name)
# or
return rebrands.get(brand_name) or brand_name
# this is forbidden - cannot use `default` keyword argument here
return rebrands.get(brand_name, default=brand_name)
assert current_brand("Jif") == "Cif"
assert current_brand("Boots") == "Boots"
我认为
.get(x) or x
更清楚,但这很大程度上是一个观点问题,所以我很好奇是否存在我没有发现的技术优点或缺点。
'恐怕不会!如果您的值为 Falsey,
or
将会短路,因此在很多值中,两个语句的行为会有所不同。
my_dict = {
'foo': 0,
'bar': "",
'baz': [],
}
x = 'foo'
print(repr(my_dict.get(x, x)))
print(repr(my_dict.get(x) or x))