Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

python - How to get all the Falsy variables without using `if` statements

Let's say I have multiple variables like:

x = 0
y = 2

if x and y:
   pass

How can I determine which of the variables are not True? I am trying to identify this without using the if statements. For the above example, I want to just get 0 (falsy value) skipping the 2 (truthy value).

question from:https://stackoverflow.com/questions/65904119/how-to-get-all-the-falsy-variables-without-using-if-statements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a tuple of all your variables. And then use itertools.filterfalse() with bool as predicate value to get all the Falsy values from tuple as:

>>> from itertools import filterfalse
>>> my_list = (1, "a", False, 2.34, "", 0)

>>> list(filterfalse(bool, my_list))
[False, '', 0]

Similarly if you need a list of all the Truthy values, you can use filter() as:

>>> my_list = (1, "a", False, 2.34, "", 0)

>>> list(filter(bool, my_list))
[1, 'a', 2.34]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...