找出整數列表中的所有偶數和奇數數字之和的 Python 程式


當需要找出整數列表中的所有偶數和奇數數字之和時,使用簡單的迭代和‘modulus’運算子。

以下是它的演示 −

示例

 現場演示

my_list = [369, 793, 2848, 4314, 57467]

print("The list is :")
print(my_list)

sum_odd = 0
sum_even = 0

for index in my_list:
   for element in str(index):

      if int(element) % 2 == 0:
         sum_even += int(element)
      else:
         sum_odd += int(element)

print("The result is :")
print("The sum of odd digits is :")
print(sum_odd)
print("The sum of odd digits is :")
print(sum_even)

輸出

The list is :
[369, 793, 2848, 4314, 57467]
The result is :
The sum of odd digits is :
54
The sum of odd digits is :
46

說明

  • 定義了一個整數列表,並在控制檯上顯示。

  • 聲明瞭兩個變數‘sum_odd’和‘sum_even’。

  • 遍歷列表,並計算奇數位和偶數位的總和。

  • 這是透過獲取元素對 2 的模運算並將其與 0 比較來完成的。

  • 這是在控制檯上顯示的輸出。

更新於:04-Sep-2021

1K+ 瀏覽

開始職業生涯

完成課程並獲得認證

立即開始
廣告