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

时间:2018-09-30 09:40:56

标签: python function for-loop

因此,我有一个名为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

第一个函数在我迭代temp_data的值并将其与temp_celsius的输出转换为摄氏度的情况下效果很好。输出为

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)

输出:

-7.222222222222222
-6.111111111111111
-6.111111111111111
-6.111111111111111
-5.0

以此类推(336个值)。

但是当我想在其他函数temp_celsius中使用temp_classifier的这些变量时,我得到了错误'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)

我在这里做错了什么?目标是将第一个功能temp_celsius的输出分配给另一个功能temp_classifier的类别。

1 个答案:

答案 0 :(得分:0)

似乎您是在浮点数上进行迭代,而不是保存在可迭代对象中的浮点数,例如列表。

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

或如果只对转换一个值感兴趣的话,直接调用float而不进行迭代:

temp_class = temp_classifier(t)
    print(temp_class)