我有一个温度列表,我试图将这些温度分为四个不同的列表:寒冷、湿滑、舒适、温暖。
这是我的代码:
#temperatures list
temperatures = [-5.4, 1.0, -1.3, -4.8, 3.9, 0.1, -4.4, 4.0, -2.2, -3.9, 4.4,
-2.5, -4.6, 5.1, 2.1, -2.4, 1.9, -3.3, -4.8, 1.0, -0.8, -2.8,
-0.1, -4.7, -5.6, 2.6, -2.7, -4.6, 3.4, -0.4, -0.9, 3.1, 2.4,
1.6, 4.2, 3.5, 2.6, 3.1, 2.2, 1.8, 3.3, 1.6, 1.5, 4.7, 4.0,
3.6, 4.9, 4.8, 5.3, 5.6, 4.1, 3.7, 7.6, 6.9, 5.1, 6.4, 3.8,
4.0, 8.6, 4.1, 1.4, 8.9, 3.0, 1.6, 8.5, 4.7, 6.6, 8.1, 4.5,
4.8, 11.3, 4.7, 5.2, 11.5, 6.2, 2.9, 4.3, 2.8, 2.8, 6.3, 2.6,
-0.0, 7.3, 3.4, 4.7, 9.3, 6.4, 5.4, 7.6, 5.2]
#Lists to store different temperatures
cold = []
slippery = []
comfortable = []
warm = []
#Assign values to respective temperature lists
for temp in temperatures:
if temp < -2:
cold = []
cold. append(temp)
elif temp >= -2 and temp < 2:
slippery = []
slippery. append(temp)
elif temp >= 2 and temp < 15:
comfortable = []
comfortable. append(temp)
elif temp >= 15:
warm = []
warm. append(temp)
print(cold)
print(slippery)
print(comfortable)
print(warm)
这是我的输出。我没有得到四个列表,而是每个列表只有一个输出。
[-4.6]
[-0.0]
[5.2]
[]
如何根据上述条件将值列表附加到每个列表?如果这是一个愚蠢的问题,请原谅我。我开始学习 Python,所以我很感激任何见解。 谢谢!
答案 0 :(得分:0)
不要每次都重置列表:) 希望这会有所帮助!
for temp in temperatures:
if temp < -2:
cold.append(temp)
elif temp >= -2 and temp < 2:
slippery.append(temp)
elif temp >= 2 and temp < 15:
comfortable.append(temp)
elif temp >= 15:
warm.append(temp)