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

标签 python if-statement search replace return

我想找到一个字符串(蓝色或红色)并将其转换为数字(1 或 2)。 我的代码 2 中有 if-Conditions。他们都是真的。所以我应该得到数字 1 和 2 作为输出。
但是取决于我把返回放在哪里,我总是得到 1 或 2,但不会同时得到 1 和 2。我错过了什么?不能同时有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)

最佳答案

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

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

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

   return color_status

关于Python 检查几个 if 条件(查找并用数字替换单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242426/

相关文章:

c - 为什么 "if (i++ && (i == 1))"是假的,而我是一个值为 1 的整数?

javascript - 重写 if else 进行切换

java - 简化 if 语句

search - 用于搜索查询更正的英语词典

php - 按前缀在数据库表中搜索字符串

python - __str__ 输出 "instance at 0x00E4F558"

python - 面向程序员的WSGI博客软件

python - 训练 tf.estimator 时记录准确度指标

python - 如何在 python 中安全地存储 LWPCookieJar 对象?

C++搜索算法——处理海量数据