Python将strin转换为Int以在函数中进行协作

2024-05-14 17:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在参加一个在线课程,有作业。我现在正在做的这项研究让我把3个数字放在一起比较,寻找匹配的数字。使用int可以很好地工作,但是当我将“2”而不是2传递到函数中时,我无法进行比较,如果我尝试转换它,我也无法进行比较

有什么想法吗

boolHomework = homework3Bonus(1,2,"two")

def homework3Bonus(a,b,c):
    print("The type of input is", type(c))
    strA = a
    strB = b
    strC = int(c)  #this isn't working
    print("The type of input is", type(a))
    print("The strings are",strA,strB,strC)
    if (strA == strB) or (strB == strC) or (strA == strC):
        print("Match")

这就产生了错误 strC=int(c) ValueError:基数为10的int()的文本无效:“2”


Tags: oroftheinputistype作业数字
2条回答

如果您想要一种功能性的方法来完成它,它还可以查找最多10个单词,那么这个解决方案将起作用

它允许将int值5int作为字符串'5'或单词表示'five'进行比较

我们将map应用于所有传入值,以便在可能的情况下将它们转换为int

然后将lambda映射到列表中的每个对组合上,该列表比较并返回每个组合的TrueFalseitertools是一个python标准库

any然后检查结果列表中是否有值为True

import itertools

NUMBER_MAP = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9,
    'ten': 10
}


def to_int(val):
    if isinstance(val, str):
        try:
            # convert number in string to int, e.g '2', '5', etc
            val = int(val)
        except ValueError:
            # convert work representation to int
            val = NUMBER_MAP.get(val.lower(), val)
    return val


def homework3Bonus(a, b, c):

    if any(map(lambda x: x[0] == x[1], itertools.combinations(map(to_int, (a, b, c)), 2))):
        print('Match')


homework3Bonus(3, 2, 'three')
homework3Bonus(3, 2, '3')
homework3Bonus(3, 2, 'two')

然后可以很容易地扩展到使用任意数量的参数,以在任意长度的值中找到匹配项

def homework3Bonus(*args):

    if any(map(lambda x: x[0] == x[1], itertools.combinations(map(to_int, args), 2))):
        print('Match')


homework3Bonus(3, 2, 1, 5, '6', 'three')

如果您有较低的约束条件,可以手动编写列表stralpha,请尝试此,如下所示:

def homework3Bonus(a,b,c):
    a, b, c = str(a), str(b), str(c)
    lst = [a, b, c]
    
    max_possible = 10
    strnum = [str(i) for i in range(max_possible)]
    stralpha = ["zero", "one", "two", three", "four", "five", "six", "seven", "eight", "nine"]
    
    for i in range(3):
        if lst[i].isalpha():
            lst[i] = strnum[stralpha.index[lst[i].lower()]]

    return len(set(lst)) == 1
            

boolHomework = homework3Bonus(1, 2, "two")        # False
boolHomework = homework3Bonus("2", 2, "two")      # True

如果您有更高的约束,您应该参考以下内容:Is there a way to convert number words to Integers?

相关问题 更多 >

    热门问题