gpt4 book ai didi

python - 如何在 AJAX 中返回时将 python 中的数组转换为与 Google Charts 兼容

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:47 25 4
gpt4 key购买 nike

我的数据库中有以下格式的数据,这只是数据的一部分(第一行用于列)

('Week Number', 'Building', 'Path', 'Scenario, 'Value' ),
(1, 'A', 1, 'Scen1', 312),
(1, 'B', 2, 'Scen2', 123),
(1, 'C', 3, 'Scen3', 34324),
(2, 'A', 1, 'Scen1', 123),
(2, 'B', 2, 'Scen2', 431),
(2, 'C', 3, 'Scen3', 555)

我不知道如何将其转换为 Google 图表格式所需的格式。

我需要以某种方式将其转换并以以下格式返回(作为数组)

['Week Number', 'A - Scen1', 'B - Scen2', 'C - Scen3'],
['1', 312, 123, 34324], # first line of the above result from database
['2', 123, 431, 555],
['3', 660, 1120, 1320],
['4', 1030, 540, 440]
.......

如您所见,场景和建筑结合在一起,并且值与周末一致

我不知道该怎么做,正在尝试做某事:

for path in result:

newPath = False
if not path in data: newPath = True
if newPath: data[ path ] = ['Week Number']

for label in result[path]:
for week_number in result[path][label]:
value = result[path][label][week_number]

但它不会带来附加值。

非常感谢您的帮助

最佳答案

根据您在问题中提供的示例数据,您可以执行以下操作:

from ast import literal_eval
with open('data.txt', 'r') as inFile:
lines = [literal_eval(elem) for elem in inFile.read().split(',\n')]
weekNumbers = sorted(set(line[0] for line in lines))
result = []
for weekNumber in weekNumbers:
tempList = []
tempList.append(weekNumber)
for line in lines:
if line[0]==weekNumber:
tempList.append(line[-1])
result.append(tempList)

for elem in result:
print(elem)

示例数据:

(1, 'A', 1, 'Scen1', 312),
(1, 'B', 2, 'Scen2', 123),
(1, 'C', 3, 'Scen3', 34324),
(2, 'A', 1, 'Scen1', 123),
(2, 'B', 2, 'Scen2', 431),
(2, 'C', 3, 'Scen3', 555)

结果:

[1, 312, 123, 34324]
[2, 123, 431, 555]

关于python - 如何在 AJAX 中返回时将 python 中的数组转换为与 Google Charts 兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55287279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com