avioid repetition converting multiple strings to floats
I am running a flask app that effectively scrapes data from https://coronavirus.data.gov.uk/ api and I have a question about formatting (trying not to be repetitive)
So the code in question takes in arguments and parameters for the data and is as follows:
"""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)
I am new to flask and apologies if the code is not great, I am still learning but the code in question is this part:
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]))
Because cases_england returns a string and then I split them and the results return a float, I am sure there is a more efficient way of doing this, maybe in a for loop, but I don't know how to do. I have tried looking but can't seem to get anywhere.
Solution 1:
If you don't want to use map
and lambda
you can just use straightforward list comprehension, e.g.,
cases_england = [f"{float(x):20.0f}" for x in cases_england.split(',')]
Solution 2:
As a note, I am not entirely certain (since I like to try out code, but can't execute yours, and I am not sure if I understood your question correctly), but you might try this:
for number, i in enumerate(cases_england):
cases_england[number] = '{:20,.0f}'.format(float(cases_england[number]))
Solution 3:
If your list grows and you want to apply a function on all elements in your list you can also use map:
cases_england = ['1', '2', '3', '41']
cases_england = list(map(lambda x: "{:20,.0f}".format(float(x)), cases_england))
'''
[' 1',
' 2',
' 3',
' 41']
'''
# Or using an f-string
list(map(lambda x: f"{float(x):20.0f}", cases_england))
[' 1',
' 2',
' 3',
' 41']