Python 程式,用於計算列表中的偶數和奇數


在本文中,我們將會了解如何解決以下問題陳述。

問題陳述 − 假設我們有一個列表,我們需要計算列表中的偶數和奇數。

以下有三種方法可供討論:

方法 1 − 使用蠻力法

示例

 線上演示

list1 = [21,3,4,6,33,2,3,1,3,76]
even_count, odd_count = 0, 0
# enhanced for loop
for num in list1:
   #even numbers
   if num % 2 == 0:
      even_count += 1
   #odd numbers
   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

方法 2 − 使用 filter() 和 lambda 表示式

示例

 線上演示

list1 = [21,3,4,6,33,2,3,1,3,76]
#odd numbers
odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))
#even numbers
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

方法 3 − 使用列表解析

示例

 線上演示

list1 = [21,3,4,6,33,2,3,1,3,76]
#copy of list elements which are odd in a new list and calculating
the length on new list
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

結論

在本文中,我們學習瞭如何計算列表中的偶數和奇數。

更新時間: 2020-07-11

5K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告