Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm số dương và âm trong danh sách Python

Bài toán: cho danh sách, đếm số lượng số dương và âm.

Cách 1: Vòng lặp for

list1 = [1, -2, -4, 6, 7, -23, 45, -0]
pos_count, neg_count = 0, 0
for num in list1:
    if num >= 0:
        pos_count += 1
    else:
        neg_count += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Positive numbers in the list: 5
Negative numbers in the list: 3

Cách 2: Vòng lặp while

list1 = [1, -2, -4, 6, 7, -23, 45, -0]
pos_count, neg_count = 0, 0
num = 0
while num < len(list1):
    if list1[num] >= 0:
        pos_count += 1
    else:
        neg_count += 1
    num += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Positive numbers in the list: 5
Negative numbers in the list: 3

Cách 3: Lambda + filter

list1 = [1, -2, -4, 6, 7, -23, 45, -0]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Positive numbers in the list: 5
Negative numbers in the list: 3

Kết luận

Đã học 3 cách đếm số dương/âm: for, while, lambda+filter.