【问题标题】:How to sort tuples [duplicate]如何对元组进行排序[重复]
【发布时间】:2016-12-17 22:59:34
【问题描述】:

我想知道如何从元组中按字母顺序对国家/地区进行排序。

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

结果应该是:

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

如果可能我可以使用 for 循环

【问题讨论】:

  • 请不要破坏你自己的问题。

标签: python for-loop tuples


【解决方案1】:

您可以使用内置排序在一行中完成此操作

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')]

【讨论】:

  • 我不能用简单的方式来做吗?使用 for 循环?
  • for 循环怎么可能比单个函数调用更简单?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
相关资源
最近更新 更多