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
192 views
in Technique[技术] by (71.8m points)

Sorted a list contains tuple in Python

I have a list like this:

list = [('Betty', 42.5), ('Andrew', 46.5), ('Zach', 49), ('Cathy',     
42.5), ('Jay', 45.5), ('Kevin', 45), ('Cassie', 41), ('Matt', 44),     
('Jamie', 44.5), ('Xavier', 45.5), ('Peter', 45.5), ('John', 42.5), 
('Jamie', 40.5), ('Joe', 40.5), ('Ellen', 44.5), ('Nancy', 35), 
('Jay', 45), ('Bryce', 43.5), ('Gordon', 37), ('Gee', 42.5)]```

How I can sort it by name (if name is same, the one with higher score comes first) in Python?

I tried this but it doesn't sort by score if same name sorted(list)


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

1 Reply

0 votes
by (71.8m points)
lst = [('Betty', 42.5), ('Andrew', 46.5), ('Zach', 49), ('Cathy', 42.5), ('Jay', 45.5), ('Kevin', 45), ('Cassie', 41), ('Matt', 44), ('Jamie', 44.5), ('Xavier', 45.5), ('Peter', 45.5), ('John', 42.5), ('Jamie', 40.5), ('Joe', 40.5), ('Ellen', 44.5), ('Nancy', 35), ('Jay', 45), ('Bryce', 43.5), ('Gordon', 37), ('Gee', 42.5)]

n0 = sorted(lst, key=lambda x: x[1],reverse=True) 
n1 = sorted(n0, key=lambda x: x[0])
print(n1)


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

...