如何在python中的嵌套循环中使用生成器

时间:2015-12-05 12:48:40

标签: python django memory-management generator nested-loops

我有一段这样的代码:

def populate_table():
    countries = CM.objects.all() # around 250 records
    for country in countries:
        destinations = Dest.objects.filter(country__iexact=country.name) # maximum 100 records
        for destination in destinations:
            i_c = IC.objects.all() # 13 million records
            for i_ca in i_c:
                o_c = OC.objects.all() # 15 million records
                for o_ca in o_c:
                    objs = []
                    tt = Time.objects.all() # 80000 records
                    for t in tt:
                        attrs = {'country': country, 'destination': destination, 'time': t, 'i_c': i_ca, 'o_c': o_ca}
                        total_amount = random.uniform(0.5000, 1.4000)
                        attrs['total_amount'] = round(total_amount, 4)
                        objs.append(FactRates(**attrs))
                    obj = FactRates.objects.bulk_create(objs)

我尝试使用发电机,但失败了。有人可以帮助我如何有效地使用发电机,这样我可以消耗更少的记忆并使其快速发挥作用 这段代码吃了我的8GB内存,我的笔记本电脑挂了。请帮帮我。

0 个答案:

没有答案