对元组列表进行排序 (Python)

Sorting a List of Tuples (Python)

我是 Python 的新手,对 lists/tuples 的排序有疑问。我有一个元组列表(见代码),需要打印三个 "city vs value" 的列表。我已经能够使用特定键来组织列表,但现在如何组织列表,然后仅使用每个元组中的特定元素来创建新列表?任何帮助表示赞赏!谢谢。

def getKey(item):
return item[0]

List = [('New York',54.9, 49.94, 2534.7),
('Los Angeles',65.4, 14.93, 3254.2),
('Chicago',49.8, 36.89, 2508.4),
('Houston',69.9, 49.77, 2577.9),
('Philadelphia',55.9, 41.53, 2498.4),
('Phoenix',75.0,  8.03, 3871.6),
('San Antonio',69.4, 32.27, 2629.2),
('San Diego',63.6, 10.34, 3054.6),
('Dallas',67.1, 37.57, 2849.7),
('San Jose',60.5, 15.82, 3061.7),
('Austin',69.3, 34.32, 2643.7)]

print sorted(List, key=getKey)

使用list comprehension

>>> List = [
...     ('New York',54.9, 49.94, 2534.7),
...     ('Los Angeles',65.4, 14.93, 3254.2),
...     ('Chicago',49.8, 36.89, 2508.4),
...     ('Houston',69.9, 49.77, 2577.9),
...     ('Philadelphia',55.9, 41.53, 2498.4),
...     ('Phoenix',75.0,  8.03, 3871.6),
...     ('San Antonio',69.4, 32.27, 2629.2),
...     ('San Diego',63.6, 10.34, 3054.6),
...     ('Dallas',67.1, 37.57, 2849.7),
...     ('San Jose',60.5, 15.82, 3061.7),
...     ('Austin',69.3, 34.32, 2643.7)
... ]
>>> [(x[0], x[2]) for x in List]  # pick first, third element only.
[('New York', 49.94),
 ('Los Angeles', 14.93),
 ('Chicago', 36.89),
 ('Houston', 49.77),
 ('Philadelphia', 41.53),
 ('Phoenix', 8.03),
 ('San Antonio', 32.27),
 ('San Diego', 10.34),
 ('Dallas', 37.57),
 ('San Jose', 15.82),
 ('Austin', 34.32)]

替代方案使用 operator.itemgetter:

>>> import operator
>>> pick = operator.itemgetter(0, 2)
>>> [pick(x) for x in List]
[('New York', 49.94),
 ('Los Angeles', 14.93),
 ('Chicago', 36.89),
 ('Houston', 49.77),
 ('Philadelphia', 41.53),
 ('Phoenix', 8.03),
 ('San Antonio', 32.27),
 ('San Diego', 10.34),
 ('Dallas', 37.57),
 ('San Jose', 15.82),
 ('Austin', 34.32)]

您可以使用列表理解创建一个新列表:

newlist = [(item[0], item[2]) for item in List]

如果您希望列表首先排序,请将 List 替换为 sorted(List, key=getKey)


顺便说一句,您可能希望将值存储在 namedtuple 而不是普通元组中,这样更容易理解:

from collections import namedtuple
City = namedtuple('City', 'name lat long elev') # or whatever your actual fields are

cities = [City('New York', 54.9, 49.94, 2534.7),
          City('Los Angeles',65.4, 14.93, 3254.2),
          ...
]

那你就可以了

sorted(cities, key=lambda item: item.name)

这里 namedtuple 的好处是您可以命名元组的元素,而不必通过索引来引用它们。