<p>我尝试此操作时,您的代码出现错误:</p>
<pre><code>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: '['
</code></pre>
<p>问题是数字列表的格式不是您期望的格式。是这样的:</p>
<pre><code>['[', '1', ',', ' ', '3', ',', ' ', '3', '1', ',', ' ', '4', '2', ',', ' ', '5', '2', ']']
</code></pre>
<p>所以<code>int('[')</code>将导致<code>ValueError</code></p>
<p>要解决这个问题,可以使用正则表达式从输入中捕获数字,map()将其转换为int,然后使用filter()过滤奇数</p>
<p>然后可以使用sum()和len()来获得奇数的总数和计数</p>
<pre><code>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)))
</code></pre>
<p>现在,当我尝试代码时,它适用于以下类型的输入:</p>
<pre><code>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
</code></pre>