Issue
scores.append((item, score))
output_file.write(scores.sort()[:20] + '\n')
I need to sort scores and write top 20 scores in a file. Above is my code and I end up with the TypeError: 'NoneType' object is not subscriptable
Thanks.
Solution
Normally the exception should be
TypeError: 'NoneType' has no attribute '__getitem__'
But however, you can not run this:
scores.sort()[:20]
That's simply because list.sort()
modifies the list in-place and does not return anything (that means it implicitly returns None
).
So you either have to place the scores.sort()
in a separate statement before the slicing operation...
scores.append((item, score))
scores.sort()
output_file.write(scores[:20] + '\n')
... or you use the built-in method sorted(...)
that does not modify the original list but returns a sorted copy.
scores.append((item, score))
output_file.write(sorted(scores)[:20] + '\n')
You should chose the first option if you want to access the sorted list again later, but you must chose the second option if you want to access the unsorted list again later. In case you won't need the list any more at all, you can chose any option.
Answered By - Byte Commander
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.