[英]How do I create a new variable from the result of a for loop with an if else statement in it in python?
I have these temperatures: 我有这些温度:
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4]
This works as a statement, but I can't get this in to a variable: 这可以作为一个语句,但是我不能将其放入变量中:
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')
I know that the following code works to get a variable from a loop: 我知道以下代码可从循环中获取变量:
x = [i for i in range(21)]
print (x)
So I tried this, but it doesn't work: 所以我尝试了这个,但是没有用:
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')]
But get this error: 但是得到这个错误:
File "", line 1 文件“”,第1行
temp_class = [i for i in temperatures: ^ SyntaxError: invalid syntax temp_class = [i对于温度中的i:^ SyntaxError:语法无效
What would be the correct code to: 1. Get a variable from my statement 2. Get both the temperatures and classes in a table similar to a tibble or data.frame in R. 什么是正确的代码:1.从我的语句中获取一个变量2.在类似于R中的tibble或data.frame的表中获取温度和类。
Thanks 谢谢
If you goal is to get these strings
into temp_class
just append them instead of print
如果您的目标是将这些
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']
You can create a function and use it in your list comprehension: 您可以创建一个函数并将其用于列表理解中:
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']
Using map() 使用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.