Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

python sort list of tuple

I am trying to sorting a list of tuple. for example, If

>>>recommendations = [('Gloria Pritchett', 2), ('Manny Delgado', 1), ('Cameron Tucker', 1), ('Luke Dunphy', 3)] 

I want to get

Luke Dunphy
Gloria Pritchett
Cameron Tucker
Manny Delgado

This is what I did:

This code only gives me

>>> [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Cameron Tucker', 1), ('Manny Delgado', 1)]

I have no idea how to append only names(strings) in sorted_list. Please help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, it sounds like you want to do this:

Given a list of (name, score) tuples, return a list of names from highest score to lowest score.

Is that right? I'm going to assume that is the questions.

Rather than go in to your code (which, when I run it, only returns ONE of the (name, score) pairs, I'll show you how I'd do it.

First in separate steps:

recommendations = [
  ('Gloria Pritchett', 2), 
  ('Manny Delgado', 1), 
  ('Cameron Tucker', 1), 
  ('Luke Dunphy', 3)]

rec2 = [(age, name) for name, age in recommendations]
print rec2
rec3 = sorted(rec2, reverse=True)
print rec3
rec4 = [name for age, name in rec3]
print rec4

This will print:

[(2, 'Gloria Pritchett'), (1, 'Manny Delgado'), (1, 'Cameron Tucker'), (3, 'Luke Dunphy')]
[(3, 'Luke Dunphy'), (2, 'Gloria Pritchett'), (1, 'Manny Delgado'), (1, 'Cameron Tucker')]
['Luke Dunphy', 'Gloria Pritchett', 'Manny Delgado', 'Cameron Tucker']

Is that what you are looking for? In my case, "Manny" got sorted before "Cameron" (unlike your intended answer), but if they got the same score, I'm hoping that doesn't matter to you. (If it does, please clarify your question)

Old timers like me might call this a variant of the Schwartzian transform. (I guess my roots in Perl are showing...)

Anyway, here's how it works:

rec2 is a "list comprehension" with score and name swapped.

rec3 uses the built-in feature of Python to sort tuples, but with reversed=True to get high-to-low sorting.

rec4 is another "list comprehension" to drop the score and return the name.

If you must, you may put it all together in a single statement:

class_rank = [name for age, name in sorted([(age, name) for name, age in recommendations], reverse=True)]
print class_rank

You are welcome to turn this in to a function, if you'd like.

Cheers!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...