Home > database >  How to create a list of sequential numbers when created from "for in" looping?
How to create a list of sequential numbers when created from "for in" looping?

Time:12-07

import requests
def trigger():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

    with open("SofaScore_Live.csv", "w ", newline="", encoding="UTF-8") as f:
        titlemenu = "id"   "\n"
        f.write(titlemenu)
        url = f'https://api.sofascore.com/api/v1/sport/football/events/live'
        response = requests.get(url, headers=headers).json()
        events = response['events']
        for event in events:
            try:
                if event['hasEventPlayerStatistics']:
                    description = event['status']['description']
                    if description == 'Halftime':
                        pass
                    else:
                        id = event['id']
                        row = str(id)   "\n"
                        f.write(row)
            except:
                pass
        f.close()

When importing game ID's via JSON API, the example result is as follows:

id
8464
7936
1657
2647

But I would like to create a column with the numbers in sequence to make it easier to see the number of lines, looking like this:

id     row
8464   1
7936   2
1657   3
2647   4

How could I generate this column taking advantage of each of the looping in for event in events:?

CodePudding user response:

As we suggested in comments, the solution is:

for i, event in enumerate(events):

and then

f.write(id   ","   i)
  • Related