newbie
newbie

Reputation: 325

Get n largest items from a list in python

I have a list that looks like this -

data = [[u'Alabama', 290060.0, 694020.0, 1452300.0, 1.093, 4.007, u'US-AL'], [u'Alaska', 46400.0, 160760.0, 300840.0, 0.871, 5.484, u'US-AK'], [u'Arizona', 320320.0, 1017020.0, 2234400.0, 1.197, 5.976, u'US-AZ'], [u'Arkansas', 295280.0, 535040.0, 896900.0, 0.6759999999999999, 2.0380000000000003, u'US-AR']]

Note - the list contains data for all 50 states. From this I want to get the 10 states with top ten NOFU2008. I want the data to look something like this-

data2008 - [[u'Alabama', 290060.0], [u'Alaska', 46400.0], [u'Arizona', 320320.0], [u'Arkansas', 295280.0]]

Note - data2008 is just an example. I want the states with highest NOFU2008.

Upvotes: 0

Views: 985

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279445

[state[0:2] for state in heapq.nlargest(10, data, operator.itemgetter(1))]

That's the "official" answer. To select 10 of 50 states the difference between heapq.nlargest and sorted is probably not a big deal. So you could go with:

data.sort(key=operator.itemgetter(1), reverse=True)
[state[0:2] for state in data[0:10]]

Upvotes: 1

Javier
Javier

Reputation: 1087

A very easy way to calculate it is:

data2008 = [stShort[0:2] for stShort in sorted(data, key=lambda stLine: stLine[1], reverse=True)][0:10]

Upvotes: 0

shaktimaan
shaktimaan

Reputation: 12092

From what i understand from the question, "NOFU" is the second element in the list after the state's name. In which case, this is what you want:

res = [[item[0], item[1]] for item in data]
print sorted(res, key=lambda x: x[1], reverse=True)[:10]

Since at most the number of elements in the list would be 50, i think this will be efficient enough.

Upvotes: 0

Related Questions