找到两个特定的子字符串并将它们添加到计数器中,然后打印出计数器



我有一个包含假冠状病毒结果(性别、年龄、身高、体重、检测结果、邮政编码(的内讧我正在尝试检索阳性女性和男性病例的数量,并将其输出到打印线上。我是编程新手,我已经尝试了很长时间让它工作,但没有成功,这是我目前的代码

样品中心体
M 87 66 133-33634
M 17 77 119-33625
M63 57 230-33603
F55 50 249-33646
M45 51 204-33675

males = 0
females = 0
positivem = 0
positivef = 0
with open("/Users/newuser/Desktop/hw1data.txt", 'r') as f:
for line in f.readlines():
words = line.lower().split()
for word in words:
if (word == "m"):
males += 1
elif (word == 'f'):
females += 1
else:
males = males
females = females
for word in words:
if ((word == 'm') and (word == '+')):
positivem += 1
elif ((word == 'f') and (word == '+')):
positivef += 1
else:
positivem = positivem 
positivef = positivef

print("{0} males have been tested and {1} females have been tested.".format(males,females))
print("Of those {0} males, {1} have tested positive.".format(males, positivem))
print("Of those {0} females, {1} have tested positive.".format(females, positive

我对您的代码做了一些修改。你需要学习if…else语句的基础知识。由于数据出现在列表"中的特定索引处;单词";,您可以直接使用索引来获取它们,不需要遍历整个列表。

如果此代码有任何错误,请告诉我。

males = females = positivef = positivem = 0
with open("/Users/newuser/Desktop/hw1data.txt", 'r') as f:
for line in f.readlines():
words = line.lower().split()
if words[0]=='M':
males+=1
if words[4]=='+':
positivem+=1
else:
females+=1
if words[4]=='+':
positivef+=1
print("{0} males have been tested and {1} females have been tested.".format(males,females))
print("Of those {0} males, {1} have tested positive.".format(males, positivem))
print("Of those {0} females, {1} have tested positive.".format(females, positivef))

最新更新