在字典中合并列表值

2024-04-26 06:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须用PHP来解决一些对我来说非常简单的问题,但是在Python中如何解决这个问题我还没有解决。你知道吗

假设我有以下词典:

data = {'year': [], 'week': [], 'value': []}

所有列表的长度始终相同,因此数据的可能值为:

{'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]}

我要做的:

迭代列表“周”时:

·如果本周的值与列表中下一周的值相同:

··用下一周覆盖该周,用下一年覆盖该年,并用与该周相同的索引求和。你知道吗

我期望得到的:

所以结果是:

{'year': ['2014', '2014'], 'week': ['44', '49'], 'value': [15, 50]}

我尝试过的:

·迭代字典,但是我对python的知识很差,我在尝试构建for循环时遇到了一些错误,比如object of type 'bool' has no len()。(我使用了构造for i in range len(dictionary.index)

·检查了itertoolscollections,但我找不到任何合适的。你知道吗

·一步一步地尝试:将字典中的饺子列表放入另一个列表,然后逐个比较项目,将值保存到另一个列表中,等等。你知道吗

有什么想法或文件要查吗?(除了继续学习python)


Tags: of数据列表fordatalen字典object
1条回答
网友
1楼 · 发布于 2024-04-26 06:24:08

使用itertools.groupby并在enumerate(d['week'])上迭代:

from itertools import groupby
from operator import itemgetter

d = {'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]}
out = {'year': [], 'week': [], 'value': []}

for k, g in groupby(enumerate(d['week']), key=itemgetter(1)):
    total = 0
    for i, x in g:
        total += d['value'][i]
    # Now `i` is the last index of the group and `x` is the last week of the group,
    # We can use these to get values from 'year' and 'week'.
    out['year'].append(d['year'][i])
    out['week'].append(x)
    out['value'].append(total)

print out
#{'week': ['44', '49'], 'value': [15, 50], 'year': ['2014', '2014']}

相关问题 更多 >

    热门问题