简体   繁体   中英

Any difference between those comparisons in python?

For instance, we hold six variables with paired values.

a, b, c = 1, 2, 3
z, x, v = 1, 2, 3

Basically, we're using == & and operators for multiple comparison;

In [6]: a == z and b == x and c == v
Out[6]: True

But we can do comparison without and logical operator, like;

In [10]: (a,b,c) == (z,x,v)
Out[10]: True

OR

In [31]: all([(a == z), (b == x), (c == v)])
Out[31]: True

All usages responses as same. But I wonder is there any differences between those comparison methods, say, logical, operational, different responses with different types of values etc..?

They will all produce the same result (assuming no exceptions are thrown either while computing the values or comparing them).

But they compute differently. This one will stop if it finds an unequal pair, so not all pairs will be compared:

a == z and b == x and c == v

If the values being compared are actually function calls, then the functions won't be called if they aren't needed for the final result.

The other two forms will perform all the computations, because you are building tuples and lists of the values:

(a,b,c) == (z,x,v)                       # makes two tuples of values
all([(a == z), (b == x), (c == v)])      # makes a list of values

I don't think, there're logical differences between the three given comparison methods. Although I would prefer the first method, I think it is clearer to understand. However, there might still be some execution time differences due to the fact, that different casts have to be called.

So I had a look at the time differences:

import time

a, b, c = 1, 2, 3
z, x, v = 1, 2, 3

iterations = 1000000

start = time.time()
for i in range(iterations):
  a == z and b == x and c == v
end = time.time()
print end - start


start = time.time()
for i in range(iterations):
  (a,b,c)==(z,x,v)
end = time.time()
print end - start


start = time.time()
for i in range(iterations):
  all([(a==z), (b==x), (c==v)])
end = time.time()
print end - start

Output:

0.268415212631
0.283325195312
0.413020133972

so basically the first method is the fastest one. Which one may easily imagine, since no "casting overhad" must be performed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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