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

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

首先为我的英语不好对不起

我想知道如何在输入的列表中得到多少个奇数例如,如果我输入[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)中有多少个奇数的程序。并且通过将最少的代码从codeA更改为一个程序,该程序在列表(codeB)上打印出奇数之和。

感谢您阅读本文,并再次感谢您解决我的问题

python python-idle
3个回答
0
投票

由于您的输入将以字符串形式出现,因此您需要将其转换为列表。这可以通过string.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.