📌  相关文章
📜  Python程序,用于查找整数列表的所有奇数和偶数之和

📅  最后修改于: 2022-05-13 01:55:20.453000             🧑  作者: Mango

Python程序,用于查找整数列表的所有奇数和偶数之和

下面的文章展示了如何给定一个整数列表,我们可以产生它所有奇数和偶数数字的总和。

方法 1:使用循环、str() 和 int()

在这种情况下,我们首先将每个元素转换为字符串,然后对其每个元素进行迭代,并通过转换为整数将其添加到相应的总和中。

Python3
# initializing list
test_list = [345, 893, 1948, 34, 2346]
  
# printing original list
print("The original list is : " + str(test_list))
  
odd_sum = 0
even_sum = 0
  
for sub in test_list:
    for ele in str(sub):
          
        # adding in particular summation according to value 
        if int(ele) % 2 == 0:
            even_sum += int(ele)
        else:
            odd_sum += int(ele)
  
# printing result 
print("Odd digit sum : " + str(odd_sum))
print("Even digit sum : " + str(even_sum))


Python3
# initializing list
test_list = [345, 893, 1948, 34, 2346]
  
# printing original list
print("The original list is : " + str(test_list))
  
odd_sum = 0
even_sum = 0
  
for sub in test_list:
      
    # sum() used to get summation of even and odd elements
    odd_sum += sum([int(ele) for ele in str(sub) if int(ele) % 2 == 1])
    even_sum += sum([int(ele) for ele in str(sub) if int(ele) % 2 == 0])
  
# printing result 
print("Odd digit sum : " + str(odd_sum))
print("Even digit sum : " + str(even_sum))


输出:

方法 2:使用循环和 sum()

在这里,我们使用 sum() 执行求和任务,循环用于执行迭代每个元素的任务。

蟒蛇3

# initializing list
test_list = [345, 893, 1948, 34, 2346]
  
# printing original list
print("The original list is : " + str(test_list))
  
odd_sum = 0
even_sum = 0
  
for sub in test_list:
      
    # sum() used to get summation of even and odd elements
    odd_sum += sum([int(ele) for ele in str(sub) if int(ele) % 2 == 1])
    even_sum += sum([int(ele) for ele in str(sub) if int(ele) % 2 == 0])
  
# printing result 
print("Odd digit sum : " + str(odd_sum))
print("Even digit sum : " + str(even_sum))

输出: