如何迭代一个列表的值,用一个函数改变它并将其添加到第二个列表中?

2024-04-26 09:40:01 发布

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

我有一张温度表:

temp_data =  [19, 21, 21, 21, 23, 23, 23, 21, 19, 21, 19, 21, 23, 27, 27, 28, 30, 30, 32, 32, 32, 32, 34, 34,
         34, 36, 36, 36, 36, 36, 36, 34, 34, 34, 34, 34, 34, 32, 30, 30, 30, 28, 28, 27, 27, 27, 23, 23,
         21, 21, 21, 19, 19, 19, 18, 18, 21, 27, 28, 30, 32, 34, 36, 37, 37, 37, 39, 39, 39, 39, 39, 39,
         41, 41, 41, 41, 41, 39, 39, 37, 37, 36, 36, 34, 34, 32, 30, 30, 28, 27, 27, 25, 23, 23, 21, 21,
         19, 19, 19, 18, 18, 18, 21, 25, 27, 28, 34, 34, 41, 37, 37, 39, 39, 39, 39, 41, 41, 39, 39, 39,
         39, 39, 41, 39, 39, 39, 37, 36, 34, 32, 28, 28, 27, 25, 25, 25, 23, 23, 23, 23, 21, 21, 21, 21,
         19, 21, 19, 21, 21, 19, 21, 27, 28, 32, 36, 36, 37, 39, 39, 39, 39, 39, 41, 41, 41, 41, 41, 41,
         41, 41, 41, 39, 37, 36, 36, 34, 32, 30, 28, 28, 27, 27, 25, 25, 23, 23, 23, 21, 21, 21, 19, 19,
         19, 19, 19, 19, 21, 23, 23, 23, 25, 27, 30, 36, 37, 37, 39, 39, 41, 41, 41, 39, 39, 41, 43, 43,
         43, 43, 43, 43, 43, 43, 43, 39, 37, 37, 37, 36, 36, 36, 36, 34, 32, 32, 32, 32, 30, 30, 28, 28,
         28, 27, 27, 27, 27, 25, 27, 27, 27, 28, 28, 28, 30, 32, 32, 32, 34, 34, 36, 36, 36, 37, 37, 37,
         37, 37, 37, 37, 37, 37, 36, 34, 30, 30, 27, 27, 25, 25, 23, 21, 21, 21, 21, 19, 19, 19, 19, 19,
         18, 18, 18, 18, 18, 19, 23, 27, 30, 32, 32, 32, 32, 32, 32, 34, 34, 34, 34, 34, 36, 36, 36, 36,
         36, 32, 32, 32, 32, 32, 32, 32, 32, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 28, 28]

我已经导入了一个模块,我用两个函数创建了这个模块,将温度从华氏度更改为摄氏度,另一个根据摄氏度分为4个类。你知道吗

from temp_functions import fahr_to_celsius, temp_classifier

因此,我还创建了一个空列表,其中按摄氏度分类的数据将显示:

temp_classes =[]

然后是for循环:

for循环应该迭代temp\ u数据中的所有值,通过

函数,然后将它们附加到空列表temp\u cellices。你知道吗

for t in temp_data:
    temp_celsius = []
    temp_celsius.append(fahr_to_celsius(t))

问题:我只得到第一个值。我尝试了range,len,=+1和其他一些,但没有运气。你知道吗

编辑: 正在从操作注释添加信息:

这是我正在进行的一项任务:

Iterate over the Fahrenheit temperature values in the temp_data list (one by one) and inside the loop: Create a new variable called temp_celsius in which you should assign the temperature in Celsius using the fahr_to_celsius function to convert the Fahrenheit temperature into Celsius. Create a new variable called temp_class in which you should assign the temperature class number (0, 1, 2, or 3) using the temp_classifier function Add the temp_class value to the temp_classes list


Tags: 模块theto函数in列表fordata
3条回答

您可以考虑使用pandas来拥有一个表视图

import pandas as pd
df = pd.DataFrame({"fahr":temp_data})

df["celsius"] = df["fahr"].apply(fahr_to_celsius)
# or
df["celsius"] = fahr_to_celsius(df["fahr"])
# or (even faster)
df["celsius"] = fahr_to_celsius(df["fahr"].values)

您在每次迭代中创建一个新列表。将列表的创建移到for循环之外:

temp_celsius = []
for t in temp_data:
    temp_celsius.append(fahr_to_celsius(t))

另一个策略是使用Python列表:

temp_celsius = [fahr_to_celsius(t) for t in temp_data]

相关问题 更多 >