python - Why does my loop only return one answer instead of answers for the entire list?
问题描述
I am trying to do a precourse assignment for lambda School and Loops are giving me the worst headache. I have a 2d list of names with heights and weights. heights were givin in cm so i used a loop to convert it to m. Then to calculate the BMI, I tried running a l;oop but it keeps giving me only the last one. Let me type the code so it makes more sense.
person_data2
[['John', 84.5, 184],
['Ryan', 81.8, 177],
['Bobby', 86.1, 190],
['Pete', 92.2, 188],
['Esther', 69.6, 159],
['Jane', 72.0, 166],
['Samantha', 51.3, 162]]
Changed heights from cm to m using the loop below and it worked
for i, person in enumerate(person_data2):
person_data2[i][2] = person_data2[i][2] / 100
print(person_data2)
[['John', 84.5, 1.84],
['Ryan', 81.8, 1.77],
['Bobby', 86.1, 1.9],
['Pete', 92.2, 1.88],
['Esther', 69.6, 1.59],
['Jane', 72.0, 1.66],
['Samantha', 51.3, 1.62]]
BMI = weight/(height^2) So I ran this
for i, person in enumerate(person_data2):
BMI2 = ((person_data2[i][1])/(person_data2[i][2]**2))
print (BMI2)
19.547325102880652
Why does it only run the last nested list BMI ie Samanthas BMI and not the rest? TBH I dont understand loops fully and changing from cm to m was a bit of copy and paste and trial and error. Could someone point me to what I am doing wrong? And if you know any resources I could use to help me get this right, I would appreciate that as well.
解决方案
Welcome to StackOverflow.
Your print()
is out of your loop, just change your code to this and place your print()
in your loop:
for i, person in enumerate(person_data2):
BMI2 = ((person_data2[i][1])/(person_data2[i][2]**2))
print (BMI2)
推荐阅读
- solr - 仅查询期间的 Apache Solr 同义词
- javascript - 在 create-react-app 中启用生产中的 javascript 源映射
- azure - Azure 托管标识 - 凭据翻转信息
- pandas - Pandas 统计的独特游戏玩家数量
- javascript - 在链接器方法之外的赛普拉斯中存储元素的文本
- windows - 手动安装 Windows 更新?
- python - Windows 任务管理器上不显示 numba jit 使用情况
- lua - 如何在不打印表的情况下获取表的名称:0xwhatever ?
- android-studio - 在android studio的新页面中有一个片段
- javascript - 如何将localstorage中的数据设置为React js中的对象数组