gpt4 book ai didi

python - 避免重复将多个字符串转换为 float

转载 作者:行者123 更新时间:2023-12-02 18:21:44 24 4
gpt4 key购买 nike

我正在运行一个 Flask 应用程序,它可以有效地从 https://coronavirus.data.gov.uk/ 中抓取数据。 api 和我有一个关于格式化的问题(尽量不要重复)

因此,相关代码接受数据的参数和参数,如下所示:

"""covid by nations"""

endpoint_england = (
'https://api.coronavirus.data.gov.uk/v1/data?'
'filters=areaType=nation;areaName=england&'
'structure={"newCases":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","dailyDeaths":"newDeaths28DaysByPublishDate","cumulativeDeaths":"cumDeaths28DaysByPublishDate"}&latestBy=cumCasesByPublishDate'
)

cases_england = get(endpoint_england,timeout=10)

if cases_england.status_code >= 400:
raise RuntimeError(f'Request failed: { cases_england.text }')

cases_england = casesengland.text.replace('}],"requestPayload":{"structure":{"newCases":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","dailyDeaths":"newDeaths28DaysByPublishDate","cumulativeDeaths":"cumDeaths28DaysByPublishDate"},"filters":[{"identifier":"areaType","operator":"=","value":"nation"},{"identifier":"areaName","operator":"=","value":"england"}],"latestBy":"cumCasesByPublishDate"}}',"").replace('{"length":1,"maxPageLimit":2500,"totalRecords":1,"data":[{','').replace('newCases','').replace('cumCasesByPublishDate','').replace('dailyDeaths','').replace('cumulativeDeaths','').replace('{','').replace(':','').replace('"','').replace(' ','')
cases_england = cases_england.split(',')

cases_england[0] = '{:20,.0f}'.format(float(cases_england[0]))
cases_england[1] = '{:20,.0f}'.format(float(cases_england[1]))
cases_england[2] = '{:20,.0f}'.format(float(cases_england[2]))
cases_england[3] = '{:20,.0f}'.format(float(cases_england[3]))

@app.route('/')
def covidcases():
return render_template('dashboard.html', cases_england=cases_england)

我是 Flask 的新手,如果代码不太好,我深表歉意,我仍在学习,但有问题的代码是这部分:

cases_england[0] = '{:20,.0f}'.format(float(cases_england[0]))
cases_england[1] = '{:20,.0f}'.format(float(cases_england[1]))
cases_england[2] = '{:20,.0f}'.format(float(cases_england[2]))
cases_england[3] = '{:20,.0f}'.format(float(cases_england[3]))

因为cases_england返回一个字符串,然后我分割它们,结果返回一个 float ,我确信有一种更有效的方法可以做到这一点,也许在for循环中,但我不知道该怎么做。我尝试过寻找,但似乎找不到任何地方。

最佳答案

如果您不想使用maplambda,您可以直接使用list comprehension ,例如,

cases_england = [f"{float(x):20.0f}" for x in cases_england.split(',')]

关于python - 避免重复将多个字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70788970/

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