>>> a
[[1990, 51.3096170908506], [1992, 51.2635305924819], [1992, 51.3374119057099], [1992, 51.8759788779255], [1993, 51.1736475226503], [1993, 51.2227948371244], [1993, 51.2227948371244], [1993, 51.8494182515316], [1993, 51.8494182515316], [1994, 51.1741251939274], [1994, 51.88740455961], [1995, 51.1782277553216], [1996, 50.8955164985205], [1996, 50.8955164985205], [1996, 51.1376528237266], [1996, 51.1740979454], [1997, 50.8955819858876], [1997, 50.8983272540453], [1997, 51.8619829641787], [1997, 51.8619829641787]]
如何找到每年的最大纬度(python): 例如:
[1992, 51.8759788779255]
答案 0 :(得分:1)
您可以使用collections.defaultdict(list)
创建一个包含按年份分组的纬度的字典:
>>> import collections
>>> result = collections.defaultdict(list)
>>> for item in data:
... result[item[0]].append(item[1])
...
>>> result
defaultdict(<type 'list'>, {1990: [51.3096170908506], 1992: [51.2635305924819, 51.3374119057099, 51.8759788779255], 1993: [51.1736475226503, 51.2227948371244, 51.2227948371244, 51.8494182515316, 51.8494182515316], 1994: [51.1741251939274, 51.88740455961], 1995: [51.1782277553216], 1996: [50.8955164985205, 50.8955164985205, 51.1376528237266, 51.1740979454], 1997: [50.8955819858876, 50.8983272540453, 51.8619829641787, 51.8619829641787]})
>>> for key, value in result.items():
... print key, max(value)
...
1990 51.3096170909
1992 51.8759788779
1993 51.8494182515
1994 51.8874045596
1995 51.1782277553
1996 51.1740979454
1997 51.8619829642
此词典将年份作为键,将列表中的纬度作为值。然后,您可以迭代该字典的内容并使用max()
获得该年度所有纬度范围内的最大纬度。
答案 1 :(得分:0)
如果由于任何原因您不想使用collections.defaultdict,则必须使用dict.setdefault提供初始值:
a = [[1990, 51.3096170908506], [1992, 51.2635305924819],
[1992, 51.3374119057099], [1992, 51.8759788779255],
[1993, 51.1736475226503], [1993, 51.2227948371244],
[1993, 51.2227948371244], [1993, 51.8494182515316],
[1993, 51.8494182515316], [1994, 51.1741251939274],
[1994, 51.88740455961], [1995, 51.1782277553216],
[1996, 50.8955164985205], [1996, 50.8955164985205],
[1996, 51.1376528237266], [1996, 51.1740979454],
[1997, 50.8955819858876], [1997, 50.8983272540453],
[1997, 51.8619829641787], [1997, 51.8619829641787]]
result = {}
for year, lat in a:
result.setdefault(year, []).append(lat)
for year in result:
print(year, max(result[year]))
'''
1990 51.3096170908506
1992 51.8759788779255
1993 51.8494182515316
1994 51.88740455961
1995 51.1782277553216
1996 51.1740979454
1997 51.8619829641787
'''
答案 2 :(得分:0)
我可以尝试这种方式:
>>> [sorted(x, key = lambda x: x[1], reverse=True)[0] for x in [[(y[0],y[1]) for y in a if y[0]==x] for x in values]]
[(1990, 51.3096170908506),
(1992, 51.8759788779255),
(1993, 51.8494182515316),
(1994, 51.88740455961),
(1995, 51.1782277553216),
(1996, 51.1740979454),
(1997, 51.8619829641787)]
>>>