检查变量是否在列表中

12

我在Python方面还比较新,我想知道是否有一种简洁的方法来测试一个值是否是列表中的值,类似于SQL WHERE子句。如果这是一个基础问题,那么请见谅。

MsUpdate.UpdateClassificationTitle in (
        'Critical Updates',
        'Feature Packs',
        'Security Updates',
        'Tools',
        'Update Rollups',
        'Updates',
        )

也就是说,我想要编写:

if MsUpdate.UpdateClassificationTitle in (
        'Critical Updates',
        'Feature Packs',
        'Security Updates',
        'Tools',
        'Update Rollups',
        'Updates'
        ):  
    then_do_something()

好的,请这样做,除了使用正确的列表语法。 - Marcin
这是一个Python的元组(tuple)还是SQL的集合(set)?因为它不是一个Python的列表(list)。 - BoltClock
1
将“(”和“)”分别更改为“ [”和“]”。 :) - 吳強福
3个回答

16

看起来已经很简洁了,但如果你要使用它超过一次,你应该给这个元组命名:

titles = ('Critical Updates',
    'Feature Packs',
    'Security Updates',
    'Tools',
    'Update Rollups',
    'Updates')

if MsUpdate.UpdateClassificationTitle in titles:  
    do_something_with_update(MsUpdate)

元组使用圆括号。如果你想要一个列表,则将其改为方括号。或者使用集合,它具有更快的查找速度。


15

这很简单:

sample = ['one', 'two', 'three', 'four']

if 'four' in sample:
   print True

4

请确保在使用例子时使用“in”而不是“is”。

username = ["Bob", "Kyle"]

name = "Kyle"

if name in username:
    print("step 1")
    login = 1
else:
    print("Invalid User")

1
你好!欢迎来到StackOverflow。请确保你的Python代码格式正确。当前的格式无法编译。你可以使用“编辑”按钮修改你的答案。 - rrauenza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接