Python检查几个ifconditions(查找并用数字替换单词)

2024-04-20 08:46:59 发布

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

我想找到一个字符串(蓝色或红色),并把它变成一个数字(1或2)。 我在代码2中有if条件。这两个都是真的。所以我应该得到数字1和2作为输出。
但取决于我把return放在哪里,我总是得到1或2,但从来没有同时得到1和2。我错过了什么?不可能同时有两个if条件吗?
例如,我的输入文本如下所示:

myInput = "I like the colors blue and red."

def check_color(document):

    for eachColor in document:

        if ("blue" in myInput):
            color_status = "1"
            #return color_status # only 1 as result

        if ("red" in myInput):
            color_status = "2"
            #return color_status # only 1 as result
        else:
            color_status = "0"
            #return color_status # only 1 as result
    #return color_status # only 2 as result

没有任何回报-->;输出:无

函数调用

color_output = check_color(myInput)
print(color_output)

Tags: inonlyreturnifcheckasstatus数字
3条回答

So I should get as an output the number 1 and 2.

不可以。一旦函数到达return语句,就会返回一个值,函数就不再继续了

Is it not possible to have 2 if-conditions at the same time?

是的。但是,如果将return语句放在if子句中,该子句的计算结果为True,则所有后续的if子句都将被忽略

Without any return > Output: None

是的。如果函数没有returnyield任何内容,它将返回None


在每种情况下,您需要仔细定义您想要的输出。例如,如果要将值列表作为输出,请初始化list并附加到它。字典将使您的解决方案更易于实现和扩展

下面是一个演示:

myInput = "I like the colors blue and red."

def check_color(var):

    c_map = {'blue': 1, 'red': 2}

    L = []
    for colour, num in c_map.items():
        if colour in var:
            L.append(num)

    return L

print(check_color(myInput))

[1, 2]

当然,您需要一个return语句来获得任何结果。问题在于这个概念:如果您想返回零个或多个值,列表将是最简单的解决方案(您的代码只是将1覆盖为2)

   color_status = []
   if "blue" in myInput:
        color_status.append("1")

   if "red" in myInput:
        color_status.append("2")

   return color_status

这是一种方法

演示:

myInput = "I like the colors blue and red."

def check_color(document):
    clr = ["blue", "red"]
    color_status = 0
    if all(i in document for i in clr):
        color_status = [1, 2]

    elif ("red" in myInput):
        color_status = 2
    elif ("blue" in myInput):
        color_status = 1

    return color_status

color_output = check_color(myInput)
print(color_output)
  • 使用all检查文本中的所有颜色
  • elif检查其他条件

相关问题 更多 >