python - 如何将列表元素加入特定的其他元素
问题描述
大家好,这是我的第一篇文章:)
我有一个小脚本,它为我创建了一个包含一些数据的列表:输出是一个列表,它的打印看起来像这样:
2018-06-07,thingA,100173
2018-06-07,thingB,35277
2018-06-08,thingA,87599
2018-06-08,thingB,35311
2018-06-09,thingA,94371
2018-06-09,thingB,45330
2018-06-10,thingA,104483
2018-06-10,thingB,51726
我正在尝试将其转换为这样的视图:
2018-06-07,100173,35277
2018-06-08,87599,35311
2018-06-09,94371,45330
2018-06-10,104483,51726
所以我想将具有相同日期的行连接到一行,其中第二个位置是thingA,第三个是thingB。它看起来很容易,但我不知道如何咬它。
我的代码计算事情 A 和 B 的发生取决于日期:
[...'2018-06-09,thingA', '2018-06-09,thingB'...]
yyyy = [[x,lista.count(x)] for x in set(lista)]
yyyy.sort()
for x in yyyy:
x = x[0] + "," + str(x[1])
亲切的问候,帕维尔
解决方案
对于 O(n) 解决方案,您可以collections.defaultdict
在列表列表中使用L
:
from collections import defaultdict
d = defaultdict(list)
for date, thing, num in L:
d[date].append(num)
res = [[date, *nums] for date, nums in d.items()]
结果:
print(res)
[['2018-06-07', 100173, 35277],
['2018-06-08', 87599, 35311],
['2018-06-09', 94371, 45330],
['2018-06-10', 104483, 51726]]
推荐阅读
- c# - Ajax 请求未在控制器类中命中正确的 Post 方法
- excel - 使用 Excel VBA 添加表格
- arrays - 如何选择多个条件以返回与这些条件匹配的一个对象
- looker - Looker 单元测试在开发中的价值与开发中的价值
- amazon-web-services - 在使用 cloudfront 在 aws 上托管 s3 静态网站时,出现错误
- node.js - 用于单独查询的节点 Mongoose 单独索引
- c# - 在 Blazor 组件中运行的后台线程和事件处理程序
- swift - 更改全局变量的图像名称 - swift
- java - 方法不预先确定集合的分配
- pdf - 从 Servlet 返回时无法下载 JSF PDF