相关疑难解决方法(0)

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

我有点词典,说:

>>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}
Run Code Online (Sandbox Code Playgroud)

我想创建一个新的字典,其中包含x和y值小于5的所有点,即点'a','b'和'd'.

根据该书,每个字典都有items()函数,它返回一个(key, pair) 元组列表:

>>> points.items()
[('a', (3, 4)), ('c', (5, 5)), ('b', (1, 2)), ('d', (3, 3))]
Run Code Online (Sandbox Code Playgroud)

所以我写了这个:

>>> 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)}
Run Code Online (Sandbox Code Playgroud)

有更优雅的方式吗?我期待Python有一些超级棒的dictionary.filter(f)功能......

python dictionary filter

190
推荐指数
7
解决办法
18万
查看次数

python:如何获取dict的子集

我有一个有许多元素的字典,我想编写一个函数,可以返回给定索引范围内的元素(将dict视为数组):

get_range(dict, begin, end):
    return {a new dict for all the indexes between begin and end}
Run Code Online (Sandbox Code Playgroud)

怎么做?

编辑:我不是要求使用密钥过滤器...例如)

{"a":"b", "c":"d", "e":"f"}

get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements)
Run Code Online (Sandbox Code Playgroud)

我不关心排序......其实我正在实现服务器端分页...

python

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

dictionary ×1

filter ×1