I am taking an extra step, that is not part of the guided project 1.
On the 10th step (Most Popular Apps by Genre on the App Store) I am trying to sort the result in ascending order: I want the result of print (genre, ':", avg_n_ratings) to be printed in ascending order.
Here’s the code I wrote
and I’ve got the following error message
TypeError: ‘float’ object is not iterable
It would help if you could post the full code segment you’re talking about, as the context of what
avg_n_ratings is and how it relates to other variables is important to help answer your question.
Here’s the full code. It returns the average number of users rating per genre
indent preformatted text by 4 spaces
for genre in genres_ios:
total = 0
for app in ios_final:
if genre_app == genre:
total += n_ratings
The result lists all the genre with their average user rating but they are not in order. I am trying to come up with a code that will help me print them in ascending (or descending order) in order to ease up the analysis.
The reason you are getting this error is because in each iteration of your loop,
avg_n_ratings gets overwritten with an integer.
If you run
sorted(avg_n_ratings) after your loop, you get an error, because
sorted() expects an iterable object (like a list) and instead we’re giving it an integer containing the value from the last iteration of your loop.
In order to achieve what you’re looking for, you’ll need to store both the genre and its average in some sort of variable that you can access after the loop runs. You could use a list or a dictionary for this, but I’d probably use a list because they have a clearly defined order.
Once you’ve done that, you can use sorted, but you’ll need to tell sorted that you want to sort on the second item in your list. To do that, we use a lambda function, which you haven’t learned yet, but we’ll learn that in a later course. You might not fully understand this code until then, but for now at least this code will do what you want
l = [
sorted(l, key=lambda x: x, reverse=True)
[['a', 3], ['c', 2], ['b', 1]]
I hope this is helpful!
I was wondering the same thing, thank you for the help. Here is my final code I hope it can help someone:
category_installs = 
for category in android_genres:
total = 0
len_category = 0
for app in android_free_apps:
category_app = app
if category_app == category:
n_installs = float(app.replace('+','').replace(',',''))
total += n_installs
len_category += 1
avg_install = int(round((total/len_category),0))
print(*sorted(category_installs,key =lambda x:x, reverse= True),sep ="\n")
I’ve also used a chained replace because of the ‘,’ and separated the printed list in new lines for better reading.