简体   繁体   English

Python:在循环中迭代条件语句

[英]Python: Iterating a conditional statement within a loop

So I have a list of values called temp_data and I have imported two functions I want to use, which are: 因此,我有一个名为temp_data的值列表,并且导入了两个要使用的函数,它们是:

# Function which converts from fahr to celsius
def fahr_to_celsius(temp_fahrenheit):
    converted_temp = (temp_fahrenheit - 32)/ 1.8 # Now we have assigned the convertable number to the variable
    return converted_temp

def temp_classifier(temp_celsius): #Function name temp_classifier, parameter temp_celsius that we later use to define the temperature
    if temp_celsius <-2: #Classifies temperatures below -2 degrees (Celsius) and returns value 0
        return 0
    elif (temp_celsius >-2) and (temp_celsius <2): #Classifies temperatures equal or higher than -2 up to +2 degrees (Celsius) and returns value 1
        return 1
    elif (temp_celsius >=2) and (temp_celsius <15): #Classifies temperatures equal or higher than +2 up to +15 degrees (Celsius) and returns value 2
        return 2
    elif temp_celsius >15: #Classifies temperatures equal or higher than +15 degrees (Celsius) and returns value 3
        return 3

The first function works well where I iterate over the values of temp_data and convert them to celsius with the output of temp_celsius . 在迭代temp_data的值并将其与temp_celsius的输出转换为temp_data地方,第一个函数很好地工作。 The output of being 存在的输出

for t in temp_data: #Takes the iteration data from temp_data
    temp_celsius=(fahr_to_celsius(t)) #Assigns output to variable
    print(temp_celsius)

output: 输出:

-7.222222222222222
-6.111111111111111
-6.111111111111111
-6.111111111111111
-5.0

and so on (336 values). 依此类推(336个值)。

But then when I want to use these variables of temp_celsius in the other function temp_classifier I get the error 'float' object is not iterable . 但是,当我想在其他函数temp_classifier使用temp_celsius这些变量时,我得到的错误'float' object is not iterable

for t in temp_celsius: #Takes the iteration data from temp_data
    temp_class=(temp_classifier(t)) #Assigns output to variable
    print(temp_class)

What am I doing wrong here? 我在这里做错了什么? The goal is to assign the outputs of the first function temp_celsius to the categories of the other function temp_classifier . 目的是将第一个函数temp_celsius的输出分配给另一个函数temp_classifier的类别。

It seems that you're iterating over a float instead floats saved in an iterable object, eg a list. 似乎您正在遍历一个float,而不是保存在可迭代对象(例如列表)中的float。

for t in temp_celsius: # Make sure temp_celsius is an iterable
    temp_class = temp_classifier(t)
    print(temp_class)

or calling directly the float without iteration if you're only interested in converting one value: 如果您只想转换一个值,则直接调用float而不进行迭代:

temp_class = temp_classifier(t)
    print(temp_class)

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

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