MattG
MattG

Reputation: 1932

How to efficiently perform multiple IF statements in python

What is a more pythonic or efficient way of comparing 2 sets of variables and doing something if they are not equal? for example, this works, but I feel like there is probably a better way than multiple if statements?

#Var set A
a=1
b=5
c=6
d=10
e=15
#Var set B
aa=2
bb=5
cc=6
dd=10
ee=14
#comparison code
if a == aa:
    #do something
if b == bb:
    #do something
if c == cc:
    #do something
if d == dd:
    #do something
if e == ee:
    #do something

My actual code will require about 50 if statements so I am looking for a more efficient method. Thanks!

EDIT

I left original code above as some people already answered, but they were not sure if #do something was different or the same code (sorry for the confusion). #do something is different. Below is more representative of what I am trying to accomplish.

#Var set A
a=1
b=5
c=6
d=10
e=15
#Var set B
aa=2
bb=5
cc=6
dd=10
ee=14
#comparison code
if a == aa:
    a = 'match'
if b == bb:
    b = 'match'
if c == cc:
    c = 'match'
if d == dd:
    d = 'match'
if e == ee:
    e = 'match'

Upvotes: 0

Views: 1225

Answers (2)

ReenigneArcher
ReenigneArcher

Reputation: 135

If all the "#do something" are the same you could do this.

A = [1, 5, 6, 10, 15]
B = [2, 5, 6, 10, 14]

x = 0
while x < len(A) and x < len(B):
    if A[x] != B[x]: #if not equal
        #do something
    x += 1

If the "#do something" is different for each one then you do something like this.

A = [1, 5, 6, 10, 15]
B = [2, 5, 6, 10, 14]
C = ['something1', 'something2', 'something2', 'something1', 'something3']

def something(string):
    if string == 'something1':
        #do something1
    elif string == 'something2':
        #do something2
    elif string == 'something3':
        #do something3

x = 0
while x < len(A) and x < len(B):
    if A[x] != B[x]: #if not equal
        something(C[x])
    x += 1

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 48028

If you're going to be comparing pairs of items, you may be able to use zip to create the pairs:

for left, right in zip([a,b,c,d,e],[aa,bb,cc,dd,ee]):
  if left == right:
    # a == aa, b == bb, etc.

If "do something" isn't the same thing each time, then add your callbacks as a third argument to zip:

for left, right, fn in zip([a,b,c,d,e],[aa,bb,cc,dd,ee],[fa,fb,fc,fd,fe]):
  if left == right:
    fn(left, right) # Assumes fa takes a and aa as arguments, etc

Upvotes: 7

Related Questions