python 列表理解 : gathering duplicate columns

标签 python

我有一个包含重复第一个元素的列表的排序列表。 目前我正在迭代它以获得解决方案。

[['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/

相关文章:

python - Selenium 文件上传失败,错误为 : "POST did not match a known command"

python - 用MySQL查询生成一维数组

Python 求质因数

python - 将 Pandas Dataframe 转换为特定格式

python - 抓取过程中返回"None"

python - 如何在 Pandas 的所有适用行中复制 groupby 的平均值

Python 多处理负载均衡器

python - 如何将终端窗口聊天应用程序(使用套接字编程构建,用 python 编写)转换为 Web 应用程序?

python - docker-compose stop 从数据库中的表中删除数据

python - 循环填充Python中的矩阵