Check variable if it is in a list
I am fairly new to Python, and I was wondering if there was a succinct way of testing a value to see if it is one of the values in the list, similar to a SQL WHERE clause. Sorry if this is a basic question.
MsUpdate.UpdateClassificationTitle in (
'Critical Updates',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates',
)
i.e, I want to write:
if MsUpdate.UpdateClassificationTitle in (
'Critical Update开发者_StackOverflows',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates'
):
then_do_something()
Seems succinct enough, but if you're using it more than once you should name the tuple:
titles = ('Critical Updates',
'Feature Packs',
'Security Updates',
'Tools',
'Update Rollups',
'Updates')
if MsUpdate.UpdateClassificationTitle in titles:
do_something_with_update(MsUpdate)
Tuples use parenthesis. If you want a list change it to square brackets. Or use a set, which has faster lookups.
It's quite straightforward:
sample = ['one', 'two', 'three', 'four']
if 'four' in sample:
print True
Make sure you are using in not is for example
username = ["Bob", "Kyle"]
name = "Kyle"
if name in username:
print("step 1")
login = 1
else:
print("Invalid User")
精彩评论