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

โปรแกรมกรองค่าที่น้อยกว่า x ในอาร์เรย์ใน Python

การกรองค่าที่น้อยกว่า x จากรายการ

ใช้ฟังก์ชัน filter() ร่วมกับ lambda เพื่อกรองค่าที่น้อยกว่า x

ตัวอย่างโค้ด

def solve(nums, x):
    left_items = filter(lambda a: a < x, nums)
    return list(left_items)

nums = [1,5,8,3,6,9,12,77,55,36,2,5,6,12,87]
x = 50
print(solve(nums, x))

ผลลัพธ์

[1, 5, 8, 3, 6, 9, 12, 36, 2, 5, 6, 12]

คำอธิบาย

filter() คืนค่า iterator ต้องแปลงเป็น list() ก่อนใช้งาน สามารถเขียนเป็น list comprehension ได้: [a for a in nums if a < x]