(Python noob)当把一串数字添加到一个列表中时,它被分割成了数字。

问题描述 投票:0回答:1

我想在赔率列表中找到偶数,或者在偶数列表中找到奇数。这就是我所得到的。

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'. 我不知道为什么

python string list integer digits
1个回答
0
投票

如果你有一个数字列表,最好把它处理成一个数字列表。

  • 列表是有用的,使用它们
    • 无需通过 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 是空的

在代码的可用性方面,我会 洁净 的输入,然后再由函数处理。 换句话说,就是将你的数字字符串隐蔽到一个列表中。之前 赋予你的功能。 这提供了更好的 分离关切事项 以获得更好的代码。

© www.soinside.com 2019 - 2024. All rights reserved.