Home > database >  how can i use loop to convert number of seasons from string to int and then take the number and assi
how can i use loop to convert number of seasons from string to int and then take the number and assi

Time:09-22

shows = [
["The Imperfects", "Science Fiction", "1", "entertaining"],
["Devil in Ohio", "Thriller", "1", "spooky"],
["The Crown", "Historical Drama", "4", "Powerful"],
["Narco-Saints", "Thriller", "1", "Entertaining"],
["In the Dark", "Crime Drama", "4", "intriguing"]]

how do i use loop to change the number of seasons from string to int and place it back into original spot in list?

CodePudding user response:

Iterate over the list of lists. For each sub-list, enumerate its elements and try to convert to int. If it succeeds, replace the original value

shows = [
    ["The Imperfects", "Science Fiction", "1", "entertaining"],
    ["Devil in Ohio", "Thriller", "1", "spooky"],
    ["The Crown", "Historical Drama", "4", "Powerful"],
    ["Narco-Saints", "Thriller", "1", "Entertaining"],
    ["In the Dark", "Crime Drama", "4", "intriguing"]]

for show in shows:
    for i, e in enumerate(show):
        try:
            show[i] = int(e)
        except ValueError:
            pass

print(shows)

Output:

[['The Imperfects', 'Science Fiction', 1, 'entertaining'], ['Devil in Ohio', 'Thriller', 1, 'spooky'], ['The Crown', 'Historical Drama', 4, 'Powerful'], ['Narco-Saints', 'Thriller', 1, 'Entertaining'], ['In the Dark', 'Crime Drama', 4, 'intriguing']]

Alternative:

If you know that the value you want to convert is at index 2 and that it's always going to be a string representation of an integer then it's even simpler:

for show in shows:
    show[2] = int(show[2])

CodePudding user response:

If your integer is always at the same place you could use this list comprehension:

new_shows = [[elem if index != 2 else int(elem) for index, elem in enumerate(show)] for show in shows]
  • Related