Python在尝试追加时一直返回空白列表



全新的python并尝试学习循环。试图从两个列表中取值来计算每个人的BMI,但总是得到一个空白列表。

heights = [184, 177, 190, 188, 159, 166]
weights = [84.9, 81.8, 86.1, 92.2, 69.6, 72.0 ]
BMIS = []
for i, bmi in BMIS:
BMIS.append(weights[i] / heights[i])
print(BMIS)

您正在循环浏览一个空列表。只需使用zip一次循环遍历每个列表。

for height, weight in zip(heights, weights):
BMIS.append(weight / height)

这种理解将产生相同的列表:

BMIS = [weight/height for height, weight in zip(heights, weights)]

列表中没有您要循环的内容。for循环正文中的代码将永远不会被执行。您可以将for循环更改为:

for height, weight in zip(heights, weights):
BMIS.append(weight/height)

您正在循环浏览BMIS,它是一个空列表。循环浏览高度或权重

heights = [184, 177, 190, 188, 159, 166]
weights = [84.9, 81.8, 86.1, 92.2, 69.6, 72.0 ]
BMIS = []
for i in range(len(heights)):
BMIS.append(weights[i] / heights[i])
print(BMIS)

假设高度和权重列表总是相同的len((,则可以将其作为范围进行循环

heights = [184, 177, 190, 188, 159, 166]
weights = [84.9, 81.8, 86.1, 92.2, 69.6, 72.0 ]
BMIS = []
for i in range(len(heights)):
BMIS.append(weights[i] / heights[i])
print(BMIS)

欢迎使用StackOverFlow。让我们检查一下你的主循环:

for i, bmi in BMIS:
BMIS.append(weights[i] / heights[i])

由于您正在初始化BMIS = [],因此您正在对一个空列表进行迭代。更好的方法是在这样的范围内迭代:

for i in range(0, len(heights)):
BMIS.append(weights[i] / heights[i])

通过这种方式,您可以访问每个列表的第i个位置,进行除法运算,并将结果附加到BMIS列表中。

最新更新