2016-12-17 104 views
-1

我想知道如何按字母順序排列元組。如何對元組進行排序

cities_countries=[('doha','qatar'),('ankara','turkey'),('rome','italy'),('brussels','belgium')] 

的結果應該是:

belgium, brussels 
italy, rome 
qatar, doha 
turkey,ankara 

如果可能的話,我可以使用循環

+0

不要惡意破壞你自己的問題。 – ShadowRanger

回答

0

您可以在同一行做到這一點使用內置的排序

cities_countries=[('doha','qatar'),('ankara','turkey'),('rome','italy'),('brussels','belgium')] 

sorted(cities_countries, key=lambda x: x[1]) 
# [('brussels', 'belgium'), 
# ('rome', 'italy'), 
# ('doha', 'qatar'), 
# ('ankara', 'turkey')] 

# and to get it in the order you want 
map(lambda x: (x[1], x[0]), sorted(cities_countries, key=lambda x: x[1])) 

# [('belgium', 'brussels'), 
# ('italy', 'rome'), 
# ('qatar', 'doha'), 
# ('turkey', 'ankara')] 
+0

我不能以簡單的方式做到這一點嗎?使用for循環? – Abdullah

+0

「for」循環怎麼會比單個函數調用更簡單? –