Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only top 5 and bottom 5 lists from Nested list?

So right I'm working with a file with a bunch of lists within a list. I'm trying to arrange them by top 5 states and bottom 5 states for total number of participants.

import csv
from operator import itemgetter #not really using this right now
crimefile = open('APExam.txt', 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
L = sorted(allRows,key=lambda x: x[1])
for item in L:
    print item[0],','.join(map(str,item[1:]))

Which prints something like this:

State  Total #,% passed,%female
Wyoming 0,0,0
New Hampshire 101,76,12
Utah 103,54,4
Mass 1067,67,18
Montana 11,55,0
Iowa 118,80,9
Alabama 126,79,17
Georgia 1261,51,18
Florida 1521,44,20
Illinois 1559,69,13
New Jersey 1582,74,15
Maine 161,67,16

This prints the file in a way that is nearly what I'm looking for but the total number of participants isn't sorted by the largest to lowest; it is sorted by looking at the first element. How do I change it to look more like:

New Jersey 1582,74,15
Illinois 1559,69,13
Florida 1521,44,20
Georgia 1261,51,18
Etc...

First time asking a question here, any help is appreciated! :) Also, I'm trying not to use the .sort() or find() function or the "in" operator-- such as "if 6 in [5, 4, 7 6] ..."

Edit*: By changing L

L = sorted(allRows,key=lambda x: int(x[1]),reverse=True)

I've gotten to the point where I have the list going in descending order:

State  Total #,% passed,%female
California 4964,76,22
Texas 3979,62,23
New York 1858,69,20
Virginia 1655,60,19
Maryland 1629,66,20
New Jersey 1582,74,15
Illinois 1559,69,13
Florida 1521,44,20

Now I can't quite seem to figure out how to only take the top 5 and bottom 5 based on these totals...

like image 560
Michael Reid Avatar asked Feb 02 '26 05:02

Michael Reid


2 Answers

For top five-

top_five = L[:5]

For bottom five-

bottom_five = L[-5:]

for detail https://www.programiz.com/python-programming/methods/built-in/slice

like image 103
Mohammad Aarif Avatar answered Feb 04 '26 17:02

Mohammad Aarif


Seems you handled the sorting to your liking, so to get the top 5 and bottom 5 elements you can use the list slicing:

>>> L = range(15)
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

>>> L[:5]
[0, 1, 2, 3, 4]

>>> L[-5:]
[10, 11, 12, 13, 14]
like image 35
famousgarkin Avatar answered Feb 04 '26 17:02

famousgarkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!