Python如何添加多个列表的和

时间:2018-11-29 13:42:05

标签: python pandas

以下是列表列表。如何将“总黑”和“总色”的总和添加到一个列表中,使“帐户ID”和“帐户名称”保持相同?

[[{'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}], 
 [{'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}]]

结果将是:

[{'Total Black': 11, 'Total Color': 6, 'Account ID': '2222', 'Account Name': 
'Moe'}, {'Total Black': 7, 'Total Color': 11, 'Account ID': '3333', 'Account 
Name': 'Larry'}, {'Total Black': 20, 'Total Color': 15, 'Account ID': 4444, 
'Account Name': 'Curly'}]

4 个答案:

答案 0 :(得分:4)

设置

thing = [
    [{'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'}, 
     {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'}, 
     {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}], 
    [{'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'}, 
     {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'}, 
     {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}]
]

非常类似于ScottBoston

pd.DataFrame(sum(thing, [])).groupby(
    ['Account ID', 'Account Name'], as_index=False
).sum().to_dict('r')

merge_with

from itertools import chain
from toolz.dicttoolz import merge_with
from collections import defaultdict

idkey = ('Account ID', 'Account Name')

x = defaultdict(list)
for d in map(dict, chain(*thing)):
  x[(*map(d.pop, idkey),)].append(d)

[{**dict(zip(idkey, key)), **merge_with(sum, *d)} for key, d in x.items()]

[{'Account ID': '2222',
  'Account Name': 'Moe',
  'Total Black': 11,
  'Total Color': 6},
 {'Account ID': '3333',
  'Account Name': 'Larry',
  'Total Black': 7,
  'Total Color': 11},
 {'Account ID': '4444',
  'Account Name': 'Curly',
  'Total Black': 20,
  'Total Color': 15}]

答案 1 :(得分:2)

让我们用熊猫吧。

#From @C14L setup:

li = [
    [
        {'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}
    ],
    [
        {'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}
    ]
]

pd.concat([pd.DataFrame(li[i]) for i in range(len(li))])\
  .groupby(['Account ID','Account Name'])\
  .sum()\
  .reset_index()\
  .to_dict(orient='records')

输出:

[{'Account ID': '2222',
  'Account Name': 'Moe',
  'Total Black': 11,
  'Total Color': 6},
 {'Account ID': '3333',
  'Account Name': 'Larry',
  'Total Black': 7,
  'Total Color': 11},
 {'Account ID': '4444',
  'Account Name': 'Curly',
  'Total Black': 20,
  'Total Color': 15}]

详细信息:

首先,我们使用列表推导和pandas数据框构造函数为带有字典的列表的原始列表的每个元素构建数据框。

接下来,使用pd.concat将这两个数据帧(在本例中为数据帧)放到一个合并的数据帧中。

使用groupby和sum来汇总“总颜色”和“总黑色”的值。

最后,重置index和to_dict以将组合的数据帧作为字典输出。

答案 2 :(得分:1)

CREATE TABLE dbo.T1
(   
    C1 INT IDENTITY(1,1)    NOT NULL,
    C2 VARCHAR(30)              NULL
)
WITH
(   DISTRIBUTION = HASH(C2),
    CLUSTERED COLUMNSTORE INDEX
);

INSERT INTO dbo.T1 VALUES (NULL);    
INSERT INTO dbo.T1 VALUES (NULL);

-- You will see two rows
SELECT * FROM dbo.T1;

作为第一个子列表的结果

li = [
    [
        {'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}
    ],
    [
        {'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}
    ]
]

result = [
    {
        'sum': x['Total Black'] + x['Total Color'],
        'Account ID': x['Account ID'],
        'Account Name': x['Account Name']
    } for x in li[0]
]

您正在寻找什么吗?

现在,您只需要遍历外部列表即可对每个包含的列表重复此操作。

答案 3 :(得分:0)

没有熊猫解决方案:

from itertools import groupby
from operator import itemgetter

orders_list = [[{'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}], 
 [{'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}]]


result_list = []

flattened_list = [item for sublist in orders_list for item in sublist]
grouper = itemgetter("Account ID", "Account Name")

for key, grp in groupby(sorted(flattened_list, key = grouper), grouper):
    temp_dict = dict(zip(["Account ID", "Account Name"], key))
    total_black_count = 0
    total_colors_count = 0
    for element in grp:
          total_black_count += element['Total Black']
          total_colors_count += element['Total Color']

    temp_dict["Total Color"] = total_colors_count
    temp_dict["Total Black"] = total_black_count
    result_list.append(temp_dict)

for dictionary in result_list:
    for key, values in dictionary.items():
        print(f"{key}: {values}")

DEMO FIDDLE