简体   繁体   English

在for循环中运行函数

[英]Running a function within a for-loop

Trying to calculate and classify BMI from a function I created, while putting it into a FOR LOOP that will open and read the file with height and weight (bmi.txt), create new variables in addition to height and weight for BMI and classification, and write that to a new file (bmi_calculated). 尝试根据我创建的函数对BMI进行计算和分类,同时将其放入FOR LOOP中,该文件将打开并读取具有高度和重量的文件(bmi.txt),并为BMI和分类创建除高度和重量之外的新变量,并将其写入新文件(bmi_calculated)。 I've got a start on the read and write file code working (though it's flipping the columns), and the function to calculate and classify BMI, but I'm not sure how to combine them to run the function within the FOR LOOP. 我已经开始了读写文件代码的工作(尽管它正在翻转列),以及用于计算和分类BMI的函数,但是我不确定如何组合它们以在FOR LOOP中运行该函数。

BMI function: BMI功能:

def BMI(height, weight):
    bmi = weight / height ** 2
    bmi = round(bmi, 1)

    if bmi <= 18.5: result = 'underweight.'
    elif 18.5 < bmi <= 25: result = 'a healthy weight.'
    elif 25 < bmi <= 29.9: result = 'overweight.'
    else: result = 'obese.'

    return [height, weight, bmi, result]

h = float(input('Your height in meters: '))
w = float(input('Your weight in kilos: '))      
my_list = ["A height of", "and a weight of", "represent a BMI of", 
"which is"]
results = BMI(h, w)
print(my_list[0], results[0], my_list[1], results[1], my_list[2], 
results[2], my_list[3], results[3])

Read/write code: 读/写代码:

infile = open("bmi.txt", "r")
outfile = open("bmi_calculated.txt", "w")
line = infile.readline()
for line in infile:
    line = line.strip()
    elements = line.split("\t")
    outfile.write(elements[1] + "\t" + elements[0] + "\n")
infile.close()
outfile.close()

EDIT: This is my attempt to call the function in the for loop, in response to one of the comments. 编辑:这是我尝试在for循环中调用函数,以响应其中一项注释。 I'm new to Python and not sure how to do this, which is why I'm asking for help: 我是Python的新手,不确定如何执行此操作,这就是为什么我寻求帮助:

def BMI(height, weight):
    bmi = weight / height ** 2
    bmi = round(bmi, 1)

    if bmi <= 18.5: result = 'underweight.'
    elif 18.5 < bmi <= 25: result = 'a healthy weight.'
    elif 25 < bmi <= 29.9: result = 'overweight.'
    else: result = 'obese.'

    return [height, weight, bmi, result]

infile = open("bmi.txt", "r")
outfile = open("bmi_calculated.txt", "w")
line = infile.readline()
for line in infile:
    line = line.strip()
    elements = line.split("\t")
    outfile.write(elements[1] + "\t" + elements[0] + "\n")
    print(BMI)
infile.close()
outfile.close()

This code doesn't add BMI or classification of overweight/obsese/etc to the outfile, and returns this "function BMI at 0x113fc4400" in repetition in the IDLE shell for the number for rows in the bmi.txt file. 此代码不会在输出文件中添加BMI或超重/肥胖/等的分类,并在IDLE外壳中重复返回此“函数BMI在0x113fc4400”,以获取bmi.txt文件中的行数。

I think it would be better if you get first all data from bmi.txt and then write the result(s) to another file. 我认为最好先从bmi.txt获取所有数据,然后将结果写入另一个文件。

my bmi.txt (two columns, tab separated)
100    100
200    200

def get_bmi_data(bmi_file):
    with open(bmi_file, "r") as f:
        raw_bmi_data = f.readlines()
    bmi_data =  [list(map(int, data.strip().split("\t"))) for data in raw_bmi_data]
    return bmi_data

bmi_data = get_bmi_data("bmi.txt")
# print(bmi_data) ->  [[100, 100], [200, 200]]

And then, for each data, you calculate and write to bmi_calculated.txt 然后,针对每个数据,计算并写入bmi_calculated.txt

def calculate_and_write(bmi_data):
    with open("bmi_calculated.txt", "w") as f:
        for data in bmi_data:
            height = data[0]
            weight = data[1]
            # change BMI method to return bmi and result
            bmi, result = BMI(height, weight)
            mytemplate = "A height of {} and a weight of {} represent a BMI of {} which is {}\n"
            to_write = mytemplate.format(height, weight, bmi, result)
            f.write(to_write)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM