我有一个列表l
,包含多个字典l = [ d1, d2, ...., d100]
,其中每个字典都用键'id'
、'address'
、'price'
定义。
现在,我想从列表l
中获取所有字典d
,其中键'price'
的值等于50。有没有比使用for循环更快的方法呢?这个处理已经封装在other for loop函数中,所以如果可能的话,我不希望有两个for loop。
函数的框架现在看起来如下:
for ... (external for loop):
results = []
for d in l:
if d['price'] == 50:
results.append(d)
除非你知道列表的结构(例如按价格排序,或者只有三个项目可以有这样的价格),否则我们不能使算法比线性时间快。所以无论如何我们必须循环。你知道吗
列表理解
我们可以使用列表理解,例如:
(这也会过滤掉没有price属性的字典)。你知道吗
熊猫
我们也可以用熊猫。Pandas是一个高效的数据帧库,在数据量很大的情况下,它的性能往往优于Python循环。在这种情况下,我们可以在datframe中加载字典,对其执行过滤,然后检索字典列表。请注意,这些将是不同的字典(即包含相同数据的其他对象)。因此数据被“复制”。你知道吗
所以这里我们用
df.price == 50
过滤。请注意,在窗帘后面有一些用于过滤的回路。你知道吗这也是一种更具声明性的方法:代码更多地解释了它在做什么,而不是如何。如何过滤并不是您的问题,语法相当优雅地显示您正在过滤数据。你知道吗
您可以使用list comprehension:
这在算法上与循环没有什么不同(它还必须迭代整个列表),但是理解是用C优化的,因此速度更快。另一种选择是使
results
成为惰性迭代器:这将不会在声明时迭代
list
。它只在您迭代results
(您只能这样做一次)时才会这样做。如果您不总是或只是部分地需要迭代results
,这可能会有所帮助。你知道吗我探索了以下方法:
Python2.7.12和Python3.5.2(不是最新版本)探讨了这些方法。在Python2中,最好的方法是方法4,而在Python3中,最好的方法是方法2(至少对于我的版本来说,它也不是最新的)。你知道吗
以下是Python 2.7.12的结果:
以下是Python 3.5.2的结果:
以下是用于获取结果的代码:
相关问题 更多 >
编程相关推荐