我试图在每个条件下得到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,我不知道如何在条件下获得完美的循环计数,我想像这样将数据存储在字典中
{
"preshift":{
"zero-2":1,
"two-4":0,
"two-5":4,
}
}发布于 2021-04-14 21:34:18
我不知道如何获得循环内部条件的完美计数
为了获得for循环的完美计数,我建议在Python.Example中使用内置函数:
>>> for count, value in enumerate(values):
... print(count, value)
...
0 a
1 b
2 c这将允许你随时保持一个完美的计数。您可以从计数0开始,也可以使用+1从1开始。
你想要的字典是字典里的一本字典。为此,创建另一个字典(调用b),并使用它来分配for循环中的值。一旦所有的值都被赋值,使用另一个字典(调用a)并在a到b中设置preshift的键值,例如a"preshift“= b,这将使它以您想要的方式进行。
在本例中,我还对如何使用变量pre_shift_count感到困惑。解决这个问题的一个简单方法是使用int类型的b字典。您将使用defaultdict(int)在python中初始化,然后在每种情况下将值增加1,例如,b[key]+=1
https://stackoverflow.com/questions/67095038
复制相似问题