简体   繁体   中英

sort a list of tuples

I have a list of tuples "degree"

[('WA', 2), ('DE', 3), ('DC', 2), ('WI', 4), ('WV', 5), ('FL', 2), ('WY', 6), ('NH', 3), ('NJ', 3), ('NM', 4), ('TX', 4), ('LA', 3), ('NC', 4), ('ND', 3), ('NE', 6), ('TN', 8), ('NY', 5), ('PA', 6), ('RI', 2), ('NV', 5), ('VA', 6), ('CO', 6), ('CA', 3), ('AL', 4), ('AR', 6), ('VT', 3), ('IL', 5), ('GA', 5), ('IN', 4), ('IA', 6), ('MA', 5), ('AZ', 4), ('ID', 6), ('CT', 3), ('ME', 1), ('MD', 5), ('OK', 6), ('OH', 5), ('UT', 5), ('MO', 8), ('MN', 4), ('MI', 3), ('KS', 4), ('MT', 4), ('MS', 4), ('SC', 2), ('KY', 7), ('OR', 4), ('SD', 6)]

I want to sort the tuple from lowest to highest (by number, not by state) so lt looks like :

[('ME', 1),....,('MO', 8)]

I tried this but it does not work, how can i fix it?

print sorted(degree)

尝试这个 -

sorted(degree, key=lambda (k,v): v)

You can try using sorted() which will return a new sorted list. We are passing an optional argument, key . Here, we are using a lambda function. sorted() will base its result in the function passed, which will evaluate each element. For example, for the first element:

('WA', 2)   # x

the function will return x[1] . In other words, 2 . Similarly for other elements.

print sorted(degree, key = lambda x : x[1])
from operator import itemgetter
sorted(degree, key=itemgetter(1))

Try this

def comp(x,y):
    return x[1] - y[1]

degree.sort(comp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM