Python- 从给定的字典中筛选出负值


作为数据分析的一部分,我们将遇到从字典中删除负值的情况。为此,我们必须循环遍历字典中的每个元素,并使用条件来检查值。可以实现以下两种方法来实现此目的。

使用 for 循环

我们使用 for 循环简单地遍历列表中的元素。在每次迭代中,我们使用 items 函数将元素的值与 0 进行比较,以检查负值。

示例

 现场演示

dict_1 = {'x':10, 'y':20, 'z':-30, 'p':-0.5, 'q':50}

print ("Given Dictionary :", str(dict_1))

final_res_1 = dict((i, j) for i, j in dict_1.items() if j >= 0)

print("After filtering the negative values from dictionary : ", str(final_res_1))

输出

运行上面的代码会给我们以下结果

Given Dictionary : {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50}
After filtering the negative values from dictionary : {'x': 10, 'y': 20, 'q': 50}

使用 lambda 函数

我们使用 lambda 函数来获得更短、更清晰的语法。在这种情况下,我们实现与上面相同的逻辑,但改为使用 lambda 函数。

示例

 现场演示

dictA = {'x':-4/2, 'y':15, 'z':-7.5, 'p':-9, 'q':17.2}

print ("\nGiven Dictionary :", dictA)

final_res = dict(filter(lambda k: k[1] >= 0.0, dictA.items()))

print("After filtering the negative values from dictionary : ", str(final_res))

输出

运行上面的代码会给我们以下结果

Given Dictionary : {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2}
After filtering the negative values from dictionary : {'y': 15, 'q': 17.2}

更新于:07-Jan-2020

394 次浏览

启动您的 职业

完成课程以获得认证

立即开始
广告
© . All rights reserved.