0

我正在尝试获取每个 if 条件中的 for 循环计数

def get(self, request, format=None):
        queryset = preshift.objects.filter(active=True,is_published=True,date_published=self.request.GET.get('date')).values()
        data = {}
        print('/////queryset_count///',queryset.count())
        pre_shift_count = 0
        for i in queryset:
            dt = i['date_published_local'].strftime("%H")
            if int(dt) in range(0,2):
                pre_shift_count+=1
                print('///1////',pre_shift_count)
                data["zero-2"]= pre_shift_count
            else:
                data["zero-2"] = 0

            if int(dt) in range(2,4):
                pre_shift_count+=1
                print('///2////',pre_shift_count)
                data["two-4"] = pre_shift_count
            else:
                data["two-4"] = 0

            if int(dt) in range(4,6):
                pre_shift_count+=1
                print('///3////',pre_shift_count)
                data["two-5"] = pre_shift_count
            else:
                data["two-5"] = 0
    
        return Response({"preshift":data})

它给了我这样的输出

    ('/////queryset_count///',4)
    (////1//,1)
    (////3//,0)
    (////3//,1)
    (////3//,2)
    (////3//,3)
    (////3//,4)
    (////3//,5)

我有四条记录,但它正在打印 5 我不知道如何在条件内获得完美的 for 循环计数,我想像这样将数据存储在字典中

{
    "preshift":{
        "zero-2":1,
        "two-4":0,
        "two-5":4,
    }
}
4

1 回答 1

1

我不知道如何在条件内获得完美的 for 循环计数

为了获得 for 循环的完美计数,我建议在.Example中使用enumerate()内置函数:Python

>>> for count, value in enumerate(values):
...     print(count, value)
...
0 a
1 b
2 c

这将使您始终保持完美计数。您可以从计数 0 开始,也可以使用 +1 从 1 开始。

您想要的字典是字典中的字典。为此,请创建另一个字典(调用 b)并使用它来分配 forloop 中的值。一旦分配了所有值,使用另一个字典(调用 a)并将 a 中的键值设置preshift为 b,例如 a["preshift"] = b。这将使它成为你想要的方式。

pre_shift_count在这种情况下,我也对您如何使用该变量感到困惑。解决这个问题的一个简单方法是使用bint 类型的字典。defaultdict(int)您将使用in进行初始化,python然后在每种情况下将值增加 1,例如,b[key]+=1

于 2021-04-14T21:34:18.407 回答