在python中,如何从带有if else语句的for循环的结果创建一个新变量?

2024-10-03 00:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些温度:

temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

这是一个语句,但我无法将其放入变量中:

for i in temperatures:
if i < -2:
    print('Cold')
elif i >= -2 and i <= 2:
    print('Slippery')
elif i >2 and i < 15:
    print('Comfortable')
else:
    print('Warm') 

我知道以下代码可以从循环中获取变量:

x = [i for i in range(21)]
print (x)

所以我试过这个,但没用:

temp_class = [i for i in temperatures:
if i < -2:
    print('Cold')
elif i >= -2 and i <= 2:
    print('Slippery')
elif i >2 and i < 15:
    print('Comfortable')
else:
    print('Warm')]

但是得到这个错误:

文件“”,第1行
温度等级=[i代表温度: ^ 语法错误:无效语法

正确的代码是什么: 1.从我的语句中获取变量 2.在一个类似于tibble或R中的data.frame的表中获取温度和类

谢谢


Tags: and代码inforif语句温度else
3条回答

使用map()

temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

def get_temp_class(i):
    if i < -2:
        return 'Cold'
    elif i >= -2 and i <= 2:
        return 'Slippery'
    elif i >2 and i < 15:
        return 'Comfortable'
    else:
        return 'Warm'

temp_class = map(get_temp_class, temperatures)

如果您的目标是将这些strings放入temp_class,只需附加它们,而不是print

temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

temp_class = []

for i in temperatures:
    if i < -2:
        temp_class.append('Cold')
    elif i >= -2 and i <= 2:
        temp_class.append('Slippery')
    elif i >2 and i < 15:
        temp_class.append('Comfortable')
    else:
        temp_class.append('Warm')

print(temp_class)
# ['Cold', 'Slippery', 'Slippery', 'Cold', 'Comfortable', 'Slippery', 'Cold']

您可以创建一个函数并在列表中使用它:

temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]

def feeling(temp):
    if temp < -2:
        return 'Cold'
    elif -2 < temp <= 2:
        return 'Slippery'
    elif 2 < temp < 15:
        return 'Comfortable'
    else:
        return 'Warm' 

[feeling(temp) for temp in temperatures]
# ['Cold', 'Slippery', 'Slippery', 'Cold', 'Comfortable', 'Slippery', 'Cold']

相关问题 更多 >