首页 > 解决方案 > 如何将列表元素加入特定的其他元素

问题描述

大家好,这是我的第一篇文章:)

我有一个小脚本,它为我创建了一个包含一些数据的列表:输出是一个列表,它的打印看起来像这样:

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])

亲切的问候,帕维尔

标签: pythonlist

解决方案


对于 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]]

推荐阅读