更有效地检查Python中if语句的概率



我有多个变量传入if, elif和else语句。假设有3个变量a, b和c,它们是包含数字的简单列表。但是我需要为每个变量的概率定义if, elif和else语句。

例如:

  • 如果其中一个变量>0对该变量做了一些事情,但传递了其他变量

基于概率,我知道所有的可能性,因此我根据这些可能性准备代码

weeks =9
a=[1,0,1,1,1,0,0,0,1]
b=[1,0,0,1,0,1,1,0,1]
c=[1,0,0,0,1,0,1,1,1]
for i in range (weeks):
if i <= 0:
(print('this is hypo'))

else:    
if(a[i] <= 0 and b[i] <= 0 and c[i] <= 0):  # no prod         0
print(a[i],b[i],c[i],'no ne is working')
elif(a[i] > 0 and b[i] <= 0 and c[i] <= 0): # only first      1
print(a[i],b[i],c[i],'only a working')
elif(a[i] > 0 and b[i] > 0 and c[i] <= 0): #first and second  1-2
print(a[i],b[i],c[i],'a and b working')
elif(a[i] > 0 and b[i] <= 0 and c[i] > 0): # first and third  1-3
print(a[i],b[i],c[i], 'a and c working')
elif(a[i] <= 0 and b[i] > 0 and c[i] <= 0): # only second     2
print(a[i],b[i],c[i],'only b working')
elif(a[i]<= 0 and b[i] > 0 and c[i] > 0): #second and third   2-3
print(a[i],b[i],c[i],'b and c working')
elif(a[i] <= 0 and b[i] <= 0 and c[i] > 0):     # only third  3
print(a[i],b[i],c[i],'only c working')
else:                            # all of are working         1-2-3
print (a[i],b[i],c[i], 'all wokring')
print('iteration number :',i)

我想要实现的是找到一种有效的方法在几个语句中传递这些可能性。处理3个变量不是一个大问题,但如果我想传递10个变量会发生什么。我需要单独定义每个概率吗?

你可以计算所有正在工作的,如果没有或所有工作,那么在某种意义上短路,如果只有一些工作,那么打印那些:

a=[1,0,1,1,1,0,0,0,1]
b=[1,0,0,1,0,1,1,0,1]
c=[1,0,0,0,1,0,1,1,1]
for abc in zip(a, b, c):
working = [x for x, y in zip("abc", abc) if y > 0]
print(
*abc,
"None" if not working else
"All" if len(working) == len(abc) else
"Only " + " and ".join(working),
"working"
)

结果:

1 1 1 All working
0 0 0 None working
1 0 0 Only a working
1 1 0 Only a and b working
1 0 1 Only a and c working
0 1 0 Only b working
0 1 1 Only b and c working
0 0 1 Only c working
1 1 1 All working

更简单的方式?

a=[1,0,1,1,1,0,0,0,1]
b=[1,0,0,1,0,1,1,0,1]
c=[1,0,0,0,1,0,1,1,1]
a1 = ['working' if int(el)>0 else 'not working' for el in a]
b1 = ['working' if int(el)>0 else 'not working' for el in b]
c1= ['working' if int(el)>0 else 'not working' for el in c]
for f, b,i,x,y,z in zip(a, b,c,a1,b1,c1):
print(f, b,i,x,y,z)

输出#

1 1 1 working working working
0 0 0 not working not working not working
1 0 0 working not working not working
1 1 0 working working not working
1 0 1 working not working working
0 1 0 not working working not working
0 1 1 not working working working
0 0 1 not working not working working
1 1 1 working working working

最新更新