首页 > 解决方案 > (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'。我不知道为什么。

标签: pythonstringlistintegerdigits

解决方案


如果您有数字列表,最好将其作为数字列表处理。

  • 列表很有用,使用它们
    • 无需通过构建一串数字stringofnumber += str(n)
    • 更改evensodds列表

我稍微重构了你的代码:



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."

注意:如果eventsodds为空,您仍然会收到错误消息

在代码可用性方面,我会在你的函数处理之前清理你的输入。换句话说,将您的数字字符串转换为列表,然后再将其提供给您的函数。这为更好的代码提供了更好的关注点分离。


推荐阅读