简体   繁体   English

如果 list = x 的任何值,请执行此操作

[英]If any value of list = x, do this

cat = [1, 2, 3]


def any_of_list(LIST):

    if ***any value of LIST*** == 2:

        print('yes')

    else:

        print('no')



any_of_list(cat)

OUTPUT = 'yes' OUTPUT = '是'

Im not sure how to enter the bold.我不确定如何输入粗体。 Please help.请帮忙。

The general case would be to use built-in any like一般情况是使用内置的any类似

def any_of_list(LIST):
    if any(x == 2 for x in LIST):
        print('yes')
    ...

Another example if any(i % 3 == 0 for i in LIST): to find if there is a multiple of 3 in the list另一个例子if any(i % 3 == 0 for i in LIST):查找列表中是否有 3 的倍数


But here as you just look for inclusion you can do但是在这里,当您只是寻找包容性时,您可以做到

def any_of_list(LIST):
    if 2 in LIST:
        print('yes')
    ...

Try尝试

if any(x == 2 for x in LIST):

If you want to solve that explicitly, do如果您想明确解决,请执行

def any_of_list(l):
    for x in l:
        if x == 2:
            return True
    return False

If you want to use the functional programming features of Python, on the other hand,另一方面,如果你想使用 Python 的函数式编程特性,

def any_of_list(l):
    return any(map(lambda x: x == 2, l))

will do the same.也会这样做。 If you want to use this approach, make sure to look up any , map and lambda in the Python Library and Language Reference.如果您想使用这种方法,请务必在 Python 库和语言参考中查找any maplambda

Beware that any_of_list is a rather bad name for that function, it is not very descriptive.请注意,对于 function, any_of_list是一个相当糟糕的名称,它的描述性不是很好。 Go for something like any_is_two . Go 类似any_is_two

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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