Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - กรองค่าลบออกจาก Dictionary ที่กำหนด

ในฐานะส่วนหนึ่งของการวิเคราะห์ข้อมูล เราจะพบสถานการณ์ที่ต้องลบค่าลบออกจาก Dictionary สำหรับสิ่งนี้ เราต้องวนลูปผ่านแต่ละองค์ประกอบใน Dictionary และใช้เงื่อนไขตรวจสอบค่า ด้านล่างมีสองวิธีที่สามารถนำไปใช้ได้

ใช้ For Loop

เราเพียงแค่วนลูปผ่านองค์ประกอบของลิสต์ด้วย for loop ในแต่ละรอบ เราใช้ฟังก์ชัน 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 Function

เราใช้ฟังก์ชัน 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}