1
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ if you reverse the first and last statement you can dedent the code a bit, amking it easier to read \$\endgroup\$ Commented Jan 27, 2022 at 22:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.