我有一个包含重复第一个元素的列表的排序列表。 目前我正在迭代它以获得解决方案。
[['5th ave', 111, -30.00, 38.00],
['5th ave', 222, -30.00, 33.00],
['6th ave', 2224, -32.00, 34.90]]
我想要一个优雅的列表理解来将其转换为基于第一个元素的列表列表:
['第五大道', [[111, -30.00, 38.00] , [222, -30.00, 33.00]]
谢谢
最佳答案
看起来像是 collections.defaultdict
的工作:
>>> from collections import defaultdict
>>> L = [['5th ave', 111, -30.00, 38.00],
... ['5th ave', 222, -30.00, 33.00],
... ['6th ave', 2224, -32.00, 34.90]]
>>> d = defaultdict(list)
>>> for sublist in L:
... d[sublist[0]].append(sublist[1:])
...
>>> print d.items()
[('5th ave', [[111, -30.0, 38.0], [222, -30.0, 33.0]]), ('6th ave', [[2224, -32.0, 34.9]])]
绝对没有理由进行列表理解。仅仅因为它的行数较少并不意味着它更 pythonic。
关于python 列表理解 : gathering duplicate columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18566317/