如何从使用列表中获得奇数

问题描述 投票:-2回答:2

我想知道如何获得输入的列表中有多少个奇数。

例如,如果我输入[1、3、31、42、52],程序将打印出“有3个奇数”

 number =list(input('list: ')) 

 total = 0 

for a in number : 
     a = int(a) 
     if a % 2 == 1 : 
      total = total + 1 
print("odd number : %d 개" % total)

这是我的最大努力,但我不知道如何对此应用“列表”:我需要将此程序更改为打印出奇数之和的程序。

我的问题是:如何通过将最小代码从codeA更改为打印列表中的奇数之和的程序(codeB,来制作一个打印列表(codeA)中的奇数数的程序? )?

python python-idle
2个回答
0
投票
由于您的输入将以字符串形式出现,因此您需要将其转换为列表。可以使用string.split()[https://docs.python.org/3/library/stdtypes.html#str.split]函数。

numbers = input('list: ') # Convert, for example: "1, 3, 5" -> ["1", " 3", " 5"] number = numbers.split(",") total = 0 for a in number: # Since these numbers are strings, they need to be converted to # integers. You may also want to strip whitespace if int(a.strip()) % 2 == 1: total = total + 1 print("odd number : ", total)


-2
投票
这里是一个解决方案。当您从带有输入的键盘中读取内容时,显然在PyCharm中会获取每个字符并将其添加到列表中。因此,如果您阅读1,2,3,4,则列表将看起来像['1',',','2'...],因此,尝试使用除外,您可以跳过任何非数字的字符。

a = list(input("list:")) no_of_odds = 0 sum_of_odds = 0 for number in a: try: if int(number) % 2 == 1: no_of_odds += 1 sum_of_odds += int(number) except ValueError: print("{0} is not a number. Skipping".format(number)) print("List: {0}".format(a)) print("No of odd numbers in list: {0}".format(no_of_odds)) print("Sum of the odd numbers in list: {0}".format(sum_of_odds))

© www.soinside.com 2019 - 2024. All rights reserved.