利用yield来实现
def test(request):
user_list = [
{'id':1,'name':'alex','age':19},
{'id':2,'name':'eric','age':18},
]
def inner(arg):
for item in arg:
yield {'id':item['id'], 'name':item['name'],'age':item['id']+item['age']}
return render(request,'test.html',{'user_list':inner(user_list)})
利用类、__iter__、yield实现
class Foo(object):
def __init__(self,data):
self.data = data
def __iter__(self):
for item in self.data:
yield item
def test(request):
user_list = [
{'id':1,'name':'alex','age':19},
{'id':2,'name':'eric','age':18},
]
obj = Foo(user_list)
return render(request,'test.html',{'user_list':obj})