gpt4 book ai didi

python - 如何根据列表中的公共(public)字符串合并列表列表,Python

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:51 25 4
gpt4 key购买 nike

我有一个列表列表,需要根据列表中的字符串进行合并以适应结构。在这种情况下,“日期”和“id”将尝试适应“字段”结构。

字段:['日期'、'id'、'展示次数'、'点击次数']

之前:

[('2015-11-01', 'id123', 'impressions', '8'), ('2015-11-01', 'id123', 
'clicks', '4'), ('2015-11-01', 'id456', 'impressions', '14'),
('2015-11-01', 'id456', 'clicks', '9')]

之后:

[('2015-11-01', 'id123', '8', '4'), ('2015-11-01', 'id456', '14', '9')]

最佳答案

>>> L  = [('2015-11-01', 'id123', 'impressions', '8'), ('2015-11-01', 'id123', 
... 'clicks', '4'), ('2015-11-01', 'id456', 'impressions', '14'),
... ('2015-11-01', 'id456', 'clicks', '9')]
>>> from collections import defaultdict
>>> D = defaultdict(list)
>>> for a, b, c, d in L:
... D[a, b].append(d)
...
>>> [k + tuple(D[k]) for k in D]
[('2015-11-01', 'id456', '14', '9'), ('2015-11-01', 'id123', '8', '4')]

展示次数和点击次数顺序不一致的情况

>>> L = [('2015-11-01', 'id123', 'impressions', '8'), ('2015-11-01', 'id123', 'clicks', '4'), ('2015-11-01', 'id456', 'clicks', '9'), ('2015-11-01', 'id456', 'impressions', '14')]
>>> from collections import defaultdict
>>> D = defaultdict(lambda: [None, None])
>>> for a, b, c, d in L:
... D[a, b][c == 'clicks'] = d
...
>>> [k + tuple(D[k]) for k in D]
[('2015-11-01', 'id456', '14', '9'), ('2015-11-01', 'id123', '8', '4')]

关于python - 如何根据列表中的公共(public)字符串合并列表列表,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35786343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com