如何根据任意条件函数过滤字典?
我有一个点的字典,比如说:
>>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}
我想创建一个新的字典,里面包含所有x和y值都小于5的点,也就是点'a'、'b'和'd'。
根据这本书,每个字典都有一个叫做items()
的函数,它会返回一个包含(键, 值)
元组的列表:
>>> 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会有一个超级好用的dictionary.filter(f)
函数……
7 个回答
27
points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
120
dict((k, v) for k, v in points.items() if all(x < 5 for x in v))
如果你在使用Python 2,并且points
可能有很多条目,你可以选择使用.iteritems()
来代替.items()
。
如果你确定每个点总是只有二维的,那么使用all(x < 5 for x in v)
可能有点多余(在这种情况下,你可以用and
来表达同样的条件),但这样做也是可以的;-)。
568
你可以使用字典推导式:
{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}