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

Chương trình Python đếm số chẵn và lẻ trong danh sách

Bài toán: cho danh sách, đếm số chẵn và lẻ.

Cách 1: Brute-force (vòng lặp for)

list1 = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
even_count, odd_count = 0, 0
for num in list1:
    if num % 2 == 0:
        even_count += 1
    else:
        odd_count += 1
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)
Even numbers available in the list: 4
Odd numbers available in the list: 6

Cách 2: filter() + lambda

list1 = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
odd_count = len(list(filter(lambda x: (x % 2 != 0), list1)))
even_count = len(list(filter(lambda x: (x % 2 == 0), list1)))
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)
Even numbers available in the list: 4
Odd numbers available in the list: 6

Cách 3: List comprehension

list1 = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
only_odd = [num for num in list1 if num % 2 == 1]
odd_count = len(only_odd)
print("Even numbers available in the list: ", len(list1) - odd_count)
print("Odd numbers available in the list: ", odd_count)
Even numbers available in the list: 4
Odd numbers available in the list: 6

Kết luận

Đã học 3 cách đếm chẵn/lẻ: for, filter+lambda, list comprehension.