python - (Python noob)将一串数字添加到列表时,它被分成数字
问题描述
我试图在赔率列表中找到偶数或在偶数列表中找到奇数。这就是我所拥有的:
def even_odd_finder(numbers):
numlist = numbers.split()
evens = []
odds = []
for m in numlist:
n = int(m)
if n % 2 != 0:
odds += str(n)
else:
evens += str(n)
if len(evens) > len(odds):
this_one = odds[0]
odd_ind = numlist.index(this_one)
return "Entry " + str(odd_ind + 1) + " is odd."
else:
no_this_one = evens[0]
even_ind = numlist.index(no_this_one)
return "Entry " + str(even_ind + 1) + " is even."
当我将一串个位数整数传递给它时,这很好用。
print(even_odd_finder("1 2 5 7 9"))
print(even_odd_finder("2 4 6 7 8"))
print(even_odd_finder("88 96 66 51 14 88 2 92 18 72 18 88 20 30 4 82 90 100 24 46"))
不过,在第三个中,我注意到我得到了 a ValueError: '5' is not in list
,因为当两位数的数字被放入偶数和赔率列表时,它们被进一步分解为数字。"8"
并且"8"
正在进入偶数,而不是"88"
,所以赔率列表中的第一个条目odds[0]
, 是'5'
而不是'51'
。我不知道为什么。
解决方案
如果您有数字列表,最好将其作为数字列表处理。
- 列表很有用,使用它们
- 无需通过构建一串数字
stringofnumber += str(n)
- 更改
evens
和odds
列表
- 无需通过构建一串数字
我稍微重构了你的代码:
def even_odd_finder(numbers):
numlist = [int(n) for n in numbers.split()]
evens = []
odds = []
for n in numlist:
if n % 2 != 0:
odds.append(n)
else:
evens.append(n)
if len(evens) > len(odds):
this_one = odds[0]
odd_index = numlist.index(this_one)
return f"Entry {odd_index + 1} is odd."
else:
no_this_one = evens[0]
even_index = numlist.index(no_this_one)
def even_odd_finder(numbers):
numlist = [int(n) for n in numbers.split()]
evens = []
odds = []
for n in numlist:
if n % 2 != 0:
odds.append(n)
else:
evens.append(n)
if len(evens) > len(odds):
this_one = odds[0]
odd_index = numlist.index(this_one)
return f"Entry {odd_index + 1} is odd."
else:
no_this_one = evens[0]
even_index = numlist.index(no_this_one)
return f"Entry {even_index + 1} is even."
return f"Entry {even_index + 1} is even."
注意:如果
events
或odds
为空,您仍然会收到错误消息
在代码可用性方面,我会在你的函数处理之前清理你的输入。换句话说,将您的数字字符串转换为列表,然后再将其提供给您的函数。这为更好的代码提供了更好的关注点分离。
推荐阅读
- python - 需要 ASCII 扑克牌在一行上打印
- android - Android on click set imageview
- scala - 获取 json 解析错误 org.json4s.package$MappingException
- pandas - Pandas:计算每个类的列百分比
- java - 单值侦听器不止一次发生
- php - Laravel 不在在线服务器上上传图片
- ruby-on-rails - 无法让 STI 在模型上充当多态关联
- javascript - 如何使用递归、休息/扩展运算符和解构将数组中的这些数字加倍?
- c++ - 如何在 C++ 代码块中从 oracle 数据库中读取表?我
- opencv - 如何配置 while 循环以使用 picamera?