我有一本积分词典,比如说:
>>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}
我想创建一个新字典,其中包含 x 和 y 值小于 5 的所有点,即点 'a'、'b' 和 'd'。
根据the book ,每个字典都有 items()
函数,它返回一个 (key, pair)
元组列表:
>>> points.items()
[('a', (3, 4)), ('c', (5, 5)), ('b', (1, 2)), ('d', (3, 3))]
所以我写了这个:
>>> for item in [i for i in points.items() if i[1][0]<5 and i[1][1]<5]:
... points_small[item[0]]=item[1]
...
>>> points_small
{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}
有没有更优雅的方式?我期待 Python 有一些 super 棒的 dictionary.filter(f)
函数...
最佳答案
您可以使用字典推导:
{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
在 Python 2 中,从 2.7 开始:
{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
https://stackoverflow.com/questions/2844516/