我面临一个问题,添加元素到我的列表
我的代码
def summary(request,):
data = []
values = {}
fruits = ['apple','mango','orange','grapes']
for i in fruits:
values['fruits'] = i
values['count'] = calculating_count(i)
data.append(values)
我所期望的是我的数据列表需要像这样
data = [{'fruits':apple,'count':10},
{'fruits':mango,'count':20},
{'fruits':orange,'count':30},
{'fruits':grapes,'count':40}]
但是我得到的是
data = [{'fruits':grapes,'count':40},
{'fruits':grapes,'count':40},
{'fruits':grapes,'count':40},
{'fruits':grapes,'count':40}]
只附加最后一个元素
def summary(request,):
data = []
fruits = ['apple','mango','orange','grapes']
for i in fruits:
values = {}
values['fruits'] = i
values['count'] = calculating_count(i)
data.append(values)
简单地说,
def summary(request, ):
fruits = ['apple', 'mango', 'orange', 'grapes']
result = [{"fruits": fruit, "count": calculating_count(fruit)} for fruit in fruits]