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

2024-03-28 11:39:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何获得输入列表中的奇数

例如,如果输入[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)的程序


Tags: 代码in程序number列表forinputif
3条回答

这里有一个解决方案。当你们用输入从键盘上读的时候,显然在PyCharm中,每个字符都会被读取并添加到列表中。因此,如果您阅读1,2,3,4,列表将看起来像['1',',','2'…],因此使用try,除了可以跳过任何不是数字的字符外

编辑!显然,在Python3中,输入的计算方法与Python2不同,因此必须逐个读取数字,否则输入将以字符分隔

no_of_vals = int(input("Numer of values: "))
a = []
for i in range(no_of_vals):
    a.append(int(input("Enter number:")))
no_of_odds = 0
sum_of_odds = 0
for number in a:
    if int(number) % 2 == 1:
        no_of_odds += 1
        sum_of_odds += int(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))

我尝试此操作时,您的代码出现错误:

list: [1, 3, 31, 42, 52]
Traceback (most recent call last):
  File "C:/Users/DELL/Documents/Python Progrms/temp.py", line 22, in <module>
    a = int(a)
ValueError: invalid literal for int() with base 10: '['

问题是数字列表的格式不是您期望的格式。是这样的:

['[', '1', ',', ' ', '3', ',', ' ', '3', '1', ',', ' ', '4', '2', ',', ' ', '5', '2', ']']

所以int('[')将导致ValueError

要解决这个问题,可以使用正则表达式从输入中捕获数字,map()将其转换为int,然后使用filter()过滤奇数

然后可以使用sum()和len()来获得奇数的总数和计数

import re

user_input = input('list: ')
number_list = map(int, re.findall(r'[-+]?\d+', user_input))
odd_number_list = list(filter(lambda number: True if number % 2 == 1 else False, number_list))

print("There are %d odd numbers and their sum is %d" % (len(odd_number_list), sum(odd_number_list)))

现在,当我尝试代码时,它适用于以下类型的输入:

list: [1, 3, 31, 42, 52]
There are 3 odd numbers and their sum is 35

list: [1,3,31,42,-52]
There are 3 odd numbers and their sum is 35

list: 1,3,-31,42,52
There are 3 odd numbers and their sum is -27

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

相关问题 更多 >