[英]How do I make this function decide if True, than divide by variable?
Im writing a program to determine the positivity rate in icu's.我正在编写一个程序来确定 icu 的阳性率。 I give a list: in_hospitals and in_icu, and I need to divide only the True values in the list by the true values to get the positivity rate %我给出了一个列表:in_hospitals 和 in_icu,我只需要将列表中的 True 值除以真实值即可得到阳性率 %
This is the list:这是列表:
in_hospitals = [True, True, False, True, False, True, True, True]
in_icu= [True, False, False, False, False, False, True, False]
The function: function:
def rate_icu(hospitals, icu):
hospitalized = len(icu) / len(hospital)
rate = hospitalized
return rate
rate = rate_icu(hospitals, icu)
print(rate) #Testing Code
The function returns 1 because it just divides 8 by 8, but I need it to divide only the True values in the list above function 返回 1,因为它只是将 8 除以 8,但我需要它仅除上面列表中的 True 值
Desired Output:所需的 Output:
33.333333333333336
You can take advantage of the fact that True
is 1
and False
is 0
.您可以利用True
为1
和False
为0
的事实。 With that, you can take the sum of the lists rather than the length:这样,您可以获取列表的总和而不是长度:
in_hospitals = [True, True, False, True, False, True, True, True]
in_icu= [True, False, False, False, False, False, True, False]
def rate_icu(hospitals, icu):
hospitalized = sum(icu) / sum(hospitals)
rate = hospitalized
return rate
rate = rate_icu(in_hospitals, in_icu)
print(rate) #Testing Code
# 0.3333333333333333
Of course if you want 33.33
you will need to multiply by 100.当然,如果你想要33.33
,你需要乘以 100。
The "obvious" way is to count
the quantity of True
in each list: “明显”的方法是count
每个列表中True
的数量:
icu.count(True) / hospital.count(True)
The "short-cut" way is to know that Boolean
is a derived from int
, with True = 1 and False = 0: simply use sum
: “捷径”的方法是知道Boolean
是从int
派生的,其中 True = 1 和 False = 0:只需使用sum
:
sum(icu) / sum(hospital)
You should use sum instead of len :您应该使用sum而不是len :
in_hospitals = [True, True, False, True, False, True, True, True]
in_icu= [True, False, False, False, False, False, True, False]
def rate_icu(hospitals, icu):
hospitalized = (sum(icu) / sum(hospital)) * 100
return hospitalized
rate = rate_icu(in_hospitals, in_icu)
print(rate) #Testing Code
You need to filter the array您需要过滤数组
in_hospitals = [True, True, False, True, False, True, True, True]
in_icu = [True, False, False, False, False, False, True, False]
def rate_icu(hospital, icu):
rate = len(icu) / len(hospital)
return rate
rate = rate_icu([x for x in in_hospitals if x is True], [x for x in in_icu if x is True])
print(rate)
I would use sum我会用总和
in_hospitals = [True, True, False, True, False, True, True, True]
in_icu= [True, False, False, False, False, False, True, False]
def rate_icu(hospitals, icu):
hospitalized = sum(icu) / sum(hospitals)
rate = hospitalized * 100
return rate
rate = rate_icu(in_hospitals, in_icu)
print(f"{rate} %")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.