如何根据任意条件函数过滤字典?

2024-04-26 06:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本要点词典,说:

>>> 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有一些超棒的dictionary.filter(f)函数。。。


Tags: thekey函数infor字典itemsitem
3条回答
dict((k, v) for k, v in points.items() if all(x < 5 for x in v))

如果您在Python 2中,可以选择调用.iteritems(),而不是.items(),并且points可能有个条目。

all(x < 5 for x in v)如果您确定每个点将始终仅为2D(在这种情况下,您可以用一个and来表示相同的约束),那么这可能是过度的,但它将工作正常;-)。

points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))

现在,在Python2.7及更高版本中,您可以使用dict理解:

{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}

在Python 3中:

{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}

相关问题 更多 >