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

โปรแกรม Python พิมพ์เลขลบในลิสต์

โจทย์: กำหนดลิสต์ พิมพ์เลขลบทั้งหมด มี 3 วิธี

วิธี 1: Enhanced For Loop

list1 = [-11, 23, -45, 23, -64, -22, -11, 24]
for num in list1:
    if num < 0:
        print(num, end=" ")

ผลลัพธ์

-11 -45 -64 -22 -11

วิธี 2: Filter และ Lambda

list1 = [-11, 23, -45, 23, -64, -22, -11, 24]
no = list(filter(lambda x: (x < 0), list1))
print("Negative numbers in the list:", no)

ผลลัพธ์

Negative numbers in the list: [-11, -45, -64, -22, -11]

วิธี 3: List Comprehension

list1 = [-11, 23, -45, 23, -64, -22, -11, 24]
nos = [num for num in list1 if num < 0]
print("Negative numbers in the list:", nos)

ผลลัพธ์

Negative numbers in the list: [-11, -45, -64, -22, -11]

สรุป

เรียนรู้ 3 วิธีพิมพ์เลขลบในลิสต์