Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Check if multiple variables have the same value

I have a set of three variables x, y, z and I want to check if they all share the same value. In my case, the value will either be 1 or 0, but I only need to know if they are all the same. Currently I'm using

if 1 == x and  1 == y and 1 == z: 
    sameness = True

Looking for the answer I've found:

if 1 in {x, y, z}:

However, this operates as

if 1 == x or  1 == y or 1 == z: 
    atleastOneMatch = True

Is it possible to check if 1 is in each: x, y, and z? Better yet, is there a more concise way of checking simply if x, y, and z are the same value?

(If it matters, I use Python 3.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you have an arbitrary sequence, use the all() function with a generator expression:

values = [x, y, z]  # can contain any number of values
if all(v == 1 for v in values):

otherwise, just use == on all three variables:

if x == y == z == 1:

If you only needed to know if they are all the same value (regardless of what value that is), use:

if all(v == values[0] for v in values):

or

if x == y == z:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...