I'm a python newbie and still learning, I have this code:
# columns are [0]title [1]year [2]rating [3]length(min) [4]genre [5]budget($mil) [6]box_office_gross($mil)
oscar_data = [
["The Shape of Water", 2017, 6.914, 123, ['sci-fi', 'drama'], 19.4, 195.243464],
["Moonlight", 2016, 6.151, 110, ['drama'], 1.5, 65.046687],
["Spotlight", 2015, 7.489, 129, ['drama', 'crime', 'history'], 20.0, 88.346473],
["Birdman", 2014, 7.604, 119, ['drama', 'comedy'], 18.0, 103.215094]
]
def filter_by_genre(data, genre):
result = []
for row in data:
genres = row[4]
if genre in genres:
result.append(row)
return result
all_genres = [
'sci-fi', 'drama', 'crime', 'history', 'comedy', 'biography',
'thriller', 'war', 'melodrama', 'action', 'adventure', 'western',
'mystery', 'horror'
]
genres_counts = []
for genre in all_genres:
count = len(filter_by_genre(oscar_data, genre))
genres_counts.append(genre)
genres_counts.append(count)
print('Genre | Number')
print('------------------------')
for row in genres_counts:
genre = row[0]
count = row[1]
print('{: <11} | {: >10}'.format(genre, count))
I've made the list shorter for the sake of the post, It supposed to count each genre in oscar_data
and print it with the genre and the count.
I thought I've done it correctly, but I can't print it because it returns the error
File "temp.py", line 63, in <module>
genre = row[0]
TypeError: 'int' object is not subscriptable
What am I supposed to do to make that int a list?
Thank you!
Your error is introduced here:
genres_counts.append(genre)
genres_counts.append(count)
You append the genre and the count as separate values, not as a collection. Replace those two lines with:
genres_counts.append((genre, count))
Better yet, use list comprehension:
genres_counts = [(genre, len(filter_by_genre(oscar_data, genre))
for genre in all_genres]