歡迎您光臨本站 註冊首頁

Python Dict找出value大於某值或key大於某值的所有項方式

←手機掃碼閱讀     f2h0b53ohn @ 2020-06-08 , reply:0

對於一個Dict:

test_dict = {1:5, 2:4, 3:3, 4:2, 5:1}

想要求key值大於等於3的所有項:

print({k:v for k, v in test_dict.items() if k>=3})

得到

{3: 3, 4: 2, 5: 1}

想要求value值大於等於3的所有項:

print({k:v for k, v in test_dict.items() if v>=3})
 {1: 5, 2: 4, 3: 3}

如果想要求k或者v某一個就取一個即可:

  # -*- coding:utf-8 -*-  __author__ = 'ShawDa'    test_dict = {1:5, 2:4, 3:3, 4:2, 5:1}  print({k:v for k, v in test_dict.items() if k>=3})  print({k:v for k, v in test_dict.items() if v>=3})  print([k for k, v in test_dict.items() if k>=3])  print([k for k, v in test_dict.items() if v>=3])  print([v for k, v in test_dict.items() if k>=3])  print([v for k, v in test_dict.items() if v>=3])

 

補充知識:列表解析式實現篩選出大於5的數[1,2,3,4,5,6,7,8,9]

list(filter(lambda x:x>5,[1,2,3,4,5,6,7,8,9]))
 #filter函數 python 中一個高階函數,過濾器 filter 函數接受一個函數func和一個列表,這個函數func的作用是對每個元素進行判斷,返回True和False來過濾掉不符合條件的元素


[f2h0b53ohn ] Python Dict找出value大於某值或key大於某值的所有項方式已經有237次圍觀

http://coctec.com/docs/python/shhow-post-237480.html