在循环python中每次迭代后更改变量的名称

时间:2017-12-08 15:08:52

标签: python json loops parsing for-loop

我希望通过创建一个能够根据列表项创建变量的循环来改善此代码

#Price for 100 
price_100 = pack['100']['product_price']
shipping_100 = pack['100']['shipment_price']
total_price_100 = price_100 + shipping_100
print(total_price_100)

#Price for 200 
price_200 = pack['200']['product_price']
shipping_200 = pack['200']['shipment_price']
total_price_200 = price_200 + shipping_200
print(total_price_200)
#etc etc etc until 1000

我想过创建一个像这样的循环:

list_quantity = ['100', '200', '300', '400', '500', '600', '700', '800', '900', '1000']
for i in list_quantity:
    price = pack[i]['product_price']
#I want to create a variable called shipping + '_' + i (e.g. price_100) for each iteration
    shipping = pack[i]['shipment_price']
#Same here, a variable called shipping + '_' + i (e.g shipping_100)
    total_price = price + shipping
    print(total_price)

0 个答案:

没有答案