在Perl我可以做這樣的事情:Python是否有像Perl一樣的定義或運算符?
foo = a // b;
什麼我不知道是如果Python有類似這樣的東西。我試過以下,但顯然它不工作:
foo = {'key1':'val1','key2':'val2'}
bar = foo['doesntexist'] or foo['key1']
而我得到的錯誤:
KeyError: 'doesntexist'
在Perl我可以做這樣的事情:Python是否有像Perl一樣的定義或運算符?
foo = a // b;
什麼我不知道是如果Python有類似這樣的東西。我試過以下,但顯然它不工作:
foo = {'key1':'val1','key2':'val2'}
bar = foo['doesntexist'] or foo['key1']
而我得到的錯誤:
KeyError: 'doesntexist'
你不需要or
可言:
bar = foo.get('doesntexist', foo['key1'])
完美,謝謝!這正是我所期待的。 –
你的方法是不工作的原因是因爲Python的布爾之前引發錯誤表達能夠被評估。而不是索引字典,您需要使用.get()
。而不是引發錯誤,.get()
回報None
,讓你的表達,以正確地評價:
bar = foo.get('doesntexist') or foo.get('key1')
需要注意的是,如果第一項的值是0
或計算結果爲false其他任何值,你的方法將失敗。如果這比你使用上述方法好。
但是,如果您不希望發生上述行爲,則必須測試第一個值是否爲None
。然而,在這一點上,倒不如簡單地這樣的邏輯解壓縮到一個單獨的函數:
def get_key(d, test_key, default_key):
"""
Given a dictionary(d), return the value of test_key.
If test_key does not exists, return the default_key
instead.
"""
if d.get(test_key) is not None:
return d.get(test_key)
return d.get(default_key)
哪位能像這樣被使用:
foo = {'key1':'val1','key2':'val2'}
bar = get_key(foo, 'doesntexist', 'key1')
該問題不是'或'它是'foo ['doesntexist']'引發錯誤。 –