【问题标题】:python loop returning wrong answerpython循环返回错误答案
【发布时间】:2022-08-17 23:24:55
【问题描述】:

如果位置的任何元素与字符串匹配,我希望我的循环返回 true。首先,我分裂以找到所需的位置。 positions = [\'founder\',\'cto\',\'partner\'] 和字符串是 person_title = \"director and cto at company\"

我的代码:

def check_title(person_title,positions):

     person_titles = person_title.split(\" \")
     for one_title in person_titles:
        for one_position_check in positions:
            if  one_position_check == one_title :
                answer = True
            
            else:
               answer = False
  return answer

答案应该是真的,但我得到的是假的。有什么帮助吗?

  • 然后,您需要在找到匹配项后立即return True

标签: python


【解决方案1】:

与其将answer 设置为True,不如简单地设置return True。否则,在找到匹配项后,不匹配项可能会再次将answer 更改为False

做这样的事情。

def check_title(person_title,positions):

     person_titles = person_title.split(" ")
     for one_title in person_titles:
        for one_position_check in positions:
            if  one_position_check == one_title :
                return True

     return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多