如何使用FOR循环生成对象?

2024-06-17 15:21:34 发布

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

我正在学习python flask,并尝试使用的重复循环动态生成字典,但我不确定如何使用python来实现,因为在其他语言中​​只需在要重复的项之前插入for的循环,但这是python的错误。请注意,我的目标有两个数据返回。我想自动生成这些内部结果吗

我想做这样的事情:

listStocks = db.execute("SELECT * FROM cars WHERE id_user = ?", userId)

car_details = [ <-- Start the loop for here

for i in range (len (list)):
    ##-----------------------------------
    ## Repete that code block
    
    brand = listStocks [i] ["brand"]
    model = listStocks [i] ["model"]

        {
            'brand': brand,
            'model': model,
        }

    ##---------------------------------------
    else: <-- if all items listed, render the template below
]

return render_template ('index.html', car = car_details)

当循环没有更多的记录插入字典时,结果将是:

car_details = [
    {
        'brand': Fiat,
        'model': Model A
    }
    {
        'brand': Volkswagen,
        'model': Model B
    }
    {
        'brand': Tesla,
        'model': Model C
    }
    {
        'brand': Ford,
        'model': Model D
    }
    {
        'brand': Ferrari,
        'model': Model E
    }
    {
        'brand': Lamborghini,
        'model': Model F
    }
    {
        'brand': BMW,
        'model': Model G
    }
]

我的真实代码:

listStocks = DB.execute("SELECT * FROM cars WHERE id_user = ?", userId)

for i in range(len(list)):

    brand = listStocks[i]["brand"]
    model = listStocks[i]["model"]

    car_details = [
        {
            'brand': brand,
            'model': model
        }
    ]

return render_template('index.html', car=car_details)

多谢各位


Tags: fromforexecutemodel字典templatedetailsrender
2条回答

问题是您正在循环内设置car_details。无论使用何种语言,你收到的结果都将是你得到的结果。你可能是说:

listStocks = DB.execute("SELECT * FROM cars WHERE id_user = ?", userId)

car_details = [] 
for i in range(len(listStocks)):

    brand = listStocks[i]["brand"]
    model = listStocks[i]["model"]

    car_details.append(
        {
            'brand': brand,
            'model': model
        }
    )

return render_template('index.html', car=car_details)
listStocks = DB.execute("SELECT * FROM cars WHERE id_user = ?", userId)
car_details = [ {'brand': item["brand"], 'model': item["model"] } for item in listStocks ]
return render_template('index.html', car=car_details)

相关问题 更多 >