开发者

Matching a variable with members of a list in Python?

开发者 https://www.devze.com 2023-03-07 08:27 出处:网络
I want to check if a value of a variable matches (==) w开发者_StackOverflow社区ith a value of any member of a given list, on a single lineuse in:

I want to check if a value of a variable matches (==) w开发者_StackOverflow社区ith a value of any member of a given list, on a single line


use in:

> lst = [1,'r']
> v = 1
> v in lst
True


EDIT: I'll leave this answer cos generator expressions are useful beasts (especially together with any and all) but if you are just testing for membership in the list then you should use in.


any(var == i for i in my_list)

Explanation:

any is a function which takes an iterable object and returns True if any element of that iterable is True.

The list comprehension [x == i for i in my_list] is a list of boolean values comparing x to each value in the list in turn. If any of them is True then x == i. So if you call any on that list you will get the answer you want.

If you change the [] to () in writing a list comprehension you get a generator object instead, which makes the values one at a time instead of constructing them in memory. And if you are passing a generator expression as the only argument to a function, you can omit the extra set of parentheses, to leave the neat syntax above.

There is also a function all.

0

精彩评论

暂无评论...
验证码 换一张
取 消