繁体   English   中英

如何在python中使用if else语句的for循环结果中创建一个新变量?

[英]How do I create a new variable from the result of a for loop with an if else statement in it in 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行
temp_class = [i对于温度中的i:^ SyntaxError:语法无效

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

谢谢

如果您的目标是将这些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']

使用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)

暂无
暂无

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

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