如何在python中高效地执行多个IF语句



比较两组变量并在它们不相等的情况下执行操作的方法是什么?例如,这是有效的,但我觉得可能有比多个if语句更好的方法?

#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

我的实际代码将需要大约50个if语句,所以我正在寻找一个更有效的方法。谢谢

编辑

我留下了上面的原始代码,因为有些人已经回答了,但他们不确定#do something是不同的还是相同的代码(很抱歉造成混淆(。CCD_ 3不同。下面更能代表我正在努力实现的目标。

#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'

如果要比较项目对,可以使用zip创建对:

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

如果";做某事;不是每次都是一样的吗,然后将回调作为第三个参数添加到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

如果所有#做某事;你也可以这样做。

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

如果"#做某事;每个人都不一样,然后你做这样的事情。

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

最新更新