Python 如何在for循环后将值附加到特定列表?

Python 如何在for循环后将值附加到特定列表?,python,list,Python,List,我有一个温度列表,我试着把它分为四个不同的列表:寒冷、湿滑、舒适、温暖 这是我的密码: #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

我有一个温度列表,我试着把它分为四个不同的列表:寒冷、湿滑、舒适、温暖

这是我的密码:

#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)
a如何根据上述标准向每个列表添加值列表?如果这是一个愚蠢的问题,请原谅我。我开始学习Python,因此我非常感谢您的任何见解。
谢谢大家!

不要每次都重置列表:)希望这有帮助

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)
温度范围内的温度:
如果温度<-2:
冷附加(温度)
elif温度>=-2和温度<2:
滑动。附加(临时)
elif温度>=2且温度<15:
舒适。附加(临时)
elif温度>=15:
温暖。附加(临时)

每次追加之前,您都会将列表重置为空列表。不要在循环中重新初始化列表。我现在明白我的错误了。非常感谢!当我将列表重置为空列表时,为什么输出列表有一个随机值?代码背后发生了什么@Barmar |逐步使用调试器,并密切关注您感兴趣的每个变量。很明显会发生什么,为什么不是一个随机值,而是每个列表中的最后一个值。
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)