我是Python的新手,并且有关于列表/元组排序的问题。我有一个元组列表(参见代码),需要打印三个列表,其中" 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)
答案 0 :(得分:2)
您可以使用列表理解创建新列表:
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
的好处是你可以命名元组的元素,而不必通过索引引用它们。
答案 1 :(得分:1)
>>> 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)]