[英]Python, Split the input string on elements of other list and remove digits from it
[英](Python noob) A string of numbers is getting split into digits when adding it to a list
我试图在赔率列表中找到偶数或在偶数列表中找到奇数。 这就是我所拥有的:
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"))
但是在第三个中,我注意到我收到了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
为空,您仍然会收到错误消息
在代码可用性方面,我会在您的 function 处理之前清理您的输入。 换句话说,将您的数字字符串转换为列表,然后再将其提供给您的 function。 这为更好的代码提供了更好的关注点分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.