python - 有什么比 dict.get(<thing>, dict.get(<other>)) 更好的吗?

标签 python dictionary

在 Python 中,

>>> x = {'spam': 'a lot'}
>>> x.get('eggs', x.get('spam'))
'a lot'

但是 .get() 组合似乎有些尴尬。

有没有更好的方式来表达“这可能是两个键之一,我不在乎哪个,只要给我值”?

最佳答案

我能想到的最“正确”的解决方案也是最丑陋的。太糟糕了。我的两个标准:

  • 避免 0 或 None 极端情况
  • 如果存在一个键则短路

尽管它很丑陋,但这实际上是最快的执行:

x['eggs'] if 'eggs' in x else x.get('spam')

timeit 结果:

>>> op       = lambda: x.get('eggs', x.get('spam'))
>>> aaron    = lambda: x.get('eggs') or x.get('spam')
>>> ndpu     = lambda: filter(None, map(x.get, ['eggs', 'spam']))[0]
>>> mhlester = lambda: x['eggs'] if 'eggs' in x else x.get('spam')
>>>
>>> timeit(op, number=100000)
0.04057041245972073
>>> timeit(aaron, number=100000)
0.04477326960257777
>>> timeit(ndpu, number=100000)
0.13210876799140614
>>> timeit(mhlester, number=100000)
0.03425499248118058

关于python - 有什么比 dict.get(<thing>, dict.get(<other>)) 更好的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259845/

相关文章:

python - 通过切片了解字符串反转

Python - 输入末尾的语法错误

python - 获取 pandas 中包含字符串的列数

Python:单击带有 urllib 或 urllib2 的按钮

android - SQLite可以处理大量数据吗

默认为键的Python字典?

python - 仅显示嵌套字典中的差异

java - 计算 Java 中 Map 中某个键的出现次数

python - 我不明白为什么我的 makemigrations 不能在 django 中工作,它显示以下错误

python - 比较 Swift 和 Python 字典对象