\$\begingroup\$
\$\endgroup\$
To collect the values of an api, I use three loopings, I would like to know if it is possible to improve this method that I use.
a = 9625897
def graph(a):
url = f'https://api.sofascore.com/api/v1/event/{a}/graph'
response = requests.get(url, headers=headers, timeout=1).json()
if 'graphPoints' in response:
minutes_list = [d['minute'] for d in response['graphPoints'][-5:]]
value_list = [d['value'] for d in response['graphPoints'][-5:]]
sum_list = sum(abs(d['value']) for d in response['graphPoints'][-5:])
else:
minutes_list = ['graph_error']
value_list = ['graph_error']
sum_list = ['graph_error']
return [minutes_list,value_list,sum_list]
asked Jan 25, 2022 at 20:57
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
You can simply use a conventional for loop, instead of comprehensions:
minutes_list = []
value_list = []
value_sum = 0
if 'graphPoints' in response:
for d in response['graphPoints'][-5:]:
minutes_list.append(d['minute'])
value_list.append(d['value'])
value_sum += abs(d['value'])
return [minutes_list, value_list, [value_sum]]
else:
return [['graph_error'], ['graph_error'], ['graph_error']]
answered Jan 25, 2022 at 21:28
-
\$\begingroup\$ if you reverse the first and last statement you can dedent the code a bit, amking it easier to read \$\endgroup\$N3buchadnezzar– N3buchadnezzar2022年01月27日 22:27:40 +00:00Commented Jan 27, 2022 at 22:27
lang-py