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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.