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}
廣告