简体   繁体   中英

Validating values present in Python List using in operator

I have written below simple code to check values present in Python List (unique_status):

if "Match" in unique_status and "Mismatch" in unique_status:
    print("Match and Mismatch both found.")
elif "Match" in unique_status:
    print("Only Match found.")
elif "Mismatch" in unique_status:
    print("Only Mismatch found.")
else:
    print("Something else is also present.)

For Value in Unique_Status = ['Match'], I am getting "Only Match Found"
For Value in Unique_Status = ['Mismatch'], I am getting "Only Mismatch Found"
For Value in Unique_Status = ['Match','Mismatch'], I am getting "Match and Mismatch both found."

However when list contains some other value also, like ['Match','Mismatch','XYZ'], then else part is not getting executed. What condition/modification is required in my code so that it checks the Unique_Status List, and executes the else condition, in case some other value is also present apart from Match and Mismatch.

if "Match" in unique_status and "Mismatch" in unique_status:
    print("Match and Mismatch both found.")
elif "Match" in unique_status:
    print("Only Match found.")
elif "Mismatch" in unique_status:
    print("Only Mismatch found.")

if any( word not in ['Match','Mismatch'] for word in unique_status ):
    print("Something else is also present.)

Followup

If you want just ONE thing printed, you should have said that. In that case, "in" is clearly the wrong operator. You need to be looking for equality:

if unique_status == ["Match"]:
    print("Only Match found.")
elif unique_status == ["Mismatch"]:
    print("Only Mismatch found.")
elif set(unique_status) == set(["Match","Mismatch"]):
    print("Match and Mismatch both found.")
else:
    print("Something else is also present.)

Because your first if condition is getting satisfied if unique_status = ['Match','Mismatch','XYZ'] Hence, the else is not working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM