需要帮助遍历嵌套列表,但

时间:2020-09-17 01:28:02

标签: iterator nested-loops

'''

patients = [[175.8, 73.4], [180.2, 59.5], [165.4, 70.2], [193.5, 120]]

def calculate_bmi(height, weight):
    return weight / ((height / 100 )**2)

def get_bmi_category(bmi):
    if bmi < 18.5:
        return "underweight"
    elif bmi < 25.0:
        return "normal weight"
    elif bmi < 30:
        return "overweighting"
    else:
        return "obesity"

for patient in patients:
    height, weight = patients[0]
    bmi = calculate_bmi(height, weight)
    bmi_category = get_bmi_category(bmi)
    print("Patient's BMI is: {} ({})".format(bmi, bmi_category))

'''

打印时,当我想要所有嵌套循环的结果时,我只会得到第一个嵌套列表的结果四次。我还能做什么?

2 个答案:

答案 0 :(得分:0)

height, weight = patients[0]更改为height, weight = patient

答案 1 :(得分:0)

问题出在下面的代码行

 height, weight = patients[0]
上面的

只会为身高和体重分配[175.8,73.4]值。 如下更新

height, weight = patient

for height, weight in patients:
#in this case you'll have to remove, height, weight = patients[0]