你可以在IF中使用AND - 检查两个条件 - python

时间:2016-01-14 13:26:14

标签: python

我正在尝试通过输入中的两个条件匹配或单词开头进行搜索:

sentence=input("What is wrong with your device?\n") # variable arrays
screenissues=["scre","displ","moni","blan"]
wifiissues=["wif","connect","signal","3g","4g"]
waterdamage=["wet","damp","rain","water","soak"]
phone=["phon","samsun","calls","mobi","mob"]

for word in sentence.split(): #splits
    if (word.startswith(tuple(screenissues)) and word.startswith(tuple(phone))): #trys to serach for two criteria at once - or works...
        print( word)
        print("you have an issue with your PHONE screen, please call us")

2 个答案:

答案 0 :(得分:2)

在做出决定之前,您需要浏览句子中的所有单词。这意味着if语句必须在for循环之后,而不是在其中:

# Key = issue type, values = keywords
issues_types = {
    'screen': ("scre","displ","moni","blan"),
    'wifi': ("wif","connect","signal","3g","4g"),
    'water damage': ("wet","damp","rain","water","soak"),
    'phone': ("phon","samsun","calls","mobi","mob"),
}
sentence = input("What is wrong with your device?\n") # variable arrays

issues = set()
for word in sentence.split():
    for issue, keywords in issues_types.items():
        if word.lower().startswith(keywords):
            issues.add(issue)

print('It looks like you have issues with', ', '.join(issues))

# Use the set operator <= (subset) to test
if {'phone', 'screen'} <= issues:
    print('You have an issue with your PHONE screen, please call us')

以下是几个示例会话:

What is wrong with your device?
my Samsung shows a blank screen
It looks like you have issues with phone, screen
You have an issue with your PHONE screen, please call us

What is wrong with your device?
My phone is soak
It looks like you have issues with phone, water damage

答案 1 :(得分:1)

是的,您可以使用“any”做出简单的决定:

if any(w.lower().startswith(s) for s in screenissues for w in sentence.split() ) and  \
    any(w.lower().startswith(p) for p in phone for w in sentence.split() ): #trys to serach for two criteria at once - or works...
    print ("you have an issue with your PHONE screen, please call us")

示例会话:

What is wrong with your device?
I have an issue with my SAMSUNG display when making calls!
you have an issue with your PHONE screen, please call us