我对Python中的for循环有问题。我想根据时间和地点对这些数据进行汇总,不包括熊猫。此数据位于MySQL数据库(MySQL工作台)中:
Time No_of_people Location
----------------------------------------
07:00 20 Liberty City
07:15 25 Liberty City
07:30 20 Liberty City
07:45 30 Liberty City
08:00 21 Liberty City
...
07:00 10 San Andreas
07:15 15 San Andreas
07:30 20 San Andreas
07:45 25 San Andreas
08:00 30 San Andreas
现在我希望它是这样的:
Time No_of_people Location
----------------------------------------
07:00 116 Liberty City
08:00 120 Liberty City
...
07:00 100 San Andreas
这就是我目前所做的:
views.py:
def getData(request):
api = 'http://localhost:8000/api/myData/'
response = requests.get(api)
myData = response.json()
time = []
no_of_people = []
location = []
for hourly in myData:
time.append(hourly['time'])
no_of_people.append(hourly['no_of_people'])
location.append(hourly['location'])
hour = []
for x in range(7,24):
hour.append(x)
uniqueLocation=[]
for x in location:
if x not in uniqueLocation:
uniqueLocation.append(x)
for uniqueIndex in uniqueLocation:
for x in hour:
sum =0
for index, t in enumerate(time):
x_time = t.split(":")[0]
if int(x_time) == x and uniqueIndex == location[index]:
sum += no_of_people[index]
print(str(sum))
json_obj = {
"time": time,
"no_of_people": no_of_people,
"location": location
}
return JsonResponse(data=json_obj)
您希望按位置分组,因此我建议您选择这种更易于可视化的格式,然后尝试从中构建表格输出(对于每个城市,对于每个时间,打印小时数和人/小时)
在处理几乎任何数据库时,请尝试为每个对象(行、表、bucket、关系,(在此处插入数据库术语)创建一个类。然后,您可以在这里隔离逻辑,而不是使主功能混乱
有了它,使用字典对位置值进行分组,最终应该能够打印它们
输出
相关问题 更多 >
编程相关推荐