如何在 for 循环中组合/连接变量和 "object path"?

How to combine / concatenate a variable and "object path" in a for loop?

我正在编写一个脚本,可以将 .json 格式转换为 .idf 格式,以便在 EnergyPlus 中进行能源模拟。作为此脚本的一部分,我需要根据给定时间之前的多个时间点和值创建计划。例如,这是我要转换的 .json 元素之一:

"BOT": {"SpacesInModel": [
               {"IndoorClimateZone": {
                     "Schedules": {
                           "PeopleSchedule": {"Timer": [
                                { "$numberInt": "0" },
                                { "$numberInt": "10" },
                                { "$numberInt": "20" },
                                { "$numberInt": "24" }
                            ],
                            "Load": [{ "$numberDouble": "0.5" }, { "$numberInt": "1" }, { "$numberDouble": "0.5" }]
}

我目前已经创建了以下代码来读取和写入 .idf 文件所需的输入,但我想将其作为 for 循环而不是一些 if 语句来执行

### Define helper function determining the number format
def IntOrDouble(path_string):
    try:
        return_value = path_string["$numberInt"]
    except Exception:
        return_value = path_string["$numberDouble"]
    return(return_value)

### Create .idf object and loop over .json format extracting schedule inputs

for item in data['BOT']['SpacesInModel']:
    InputFile.newidfobject("Schedule:Day:Interval") #.idf object
    DailySchedule = InputFile.idfobjects["Schedule:Day:Interval"][-1]
    
    People_Time = item["IndoorClimateZone"]["Schedules"]["PeopleSchedule"]["Timer"]
    People_Load = item["IndoorClimateZone"]["Schedules"]["PeopleSchedule"]["Load"]

    if len(People_Time) >= 0 and len(People_Time) != 0:
        DailySchedule.Time_2 = IntOrDouble(People_Time[0]) 
        
    if len(People_Time) >= 1 and len(People_Time) != 1:
        DailySchedule.Time_2 = IntOrDouble(People_Time[1])
        DailySchedule.Value_Until_Time_2 = IntOrDouble(People_Load[0])
        
    if len(People_Time) >= 2 and len(People_Time) != 2:
        DailySchedule.Time_3 = IntOrDouble(People_Time[2])
        DailySchedule.Value_Until_Time_3 = IntOrDouble(People_Load[1])

    if len(People_Time) >= 3 and len(People_Time) != 3:
        DailySchedule.Time_4 = IntOrDouble(People_Time[3])
        DailySchedule.Value_Until_Time_4 = IntOrDouble(People_Load[2])

    if len(People_Time) >= 4 and len(People_Time) != 4:
        DailySchedule.Time_5 = IntOrDouble(People_Time[4])
        DailySchedule.Value_Until_Time_4 = IntOrDouble(People_Load[3])

我的问题是我不知道如何将变量 DailySchedule 与可变对象名称/路径“连接”,例如Time_1Load_4Time_i Load_i 的索引必须跟在 for 循环的索引之后。截至目前,这是我得到的最接近的(知道这不是真正的解决方案:-))

for i in range(len(People_Time)):
        DailySchedule."Time_{0}".format(i+1) = IntOrDouble(People_Time[i+1])
        DailySchedule."Load_{0}".format(i+1) = IntOrDouble(People_Load[i]) 

您可以使用 pythons "F-strings" to add a variable to the string and 来访问字典中的项目。

for i in range(len(People_Time)):
    DailySchedule[f"Time_{i+1}"] = IntOrDouble(People_Time[i+1])
    DailySchedule[f"Time_{i}"] = IntOrDouble(People_Load[i])