Last active
February 19, 2020 11:22
-
-
Save ruchej/2f04231d84944e2093e9c30e09bd8371 to your computer and use it in GitHub Desktop.
Группировка именнованного кортежа по ключу
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from collections import OrderedDict, namedtuple | |
from pprint import pprint | |
def group_by_key(iterable, key, sum_field): | |
"""Группирует список по полю key и суммирует по полю sum_field | |
iterable - список именованных кортежей | |
key - строка, название общего поля для группировки | |
sum_field - строка, название поля содержащие кол-во, которое будет суммироваться | |
было: | |
Pans(cpos=2, name='Стойка правая', length=584, width=400, cnt=1), | |
Pans(cpos=2, name='Стойка левая', length=584, width=400, cnt=1), | |
стало: | |
Pans(cpos=2, name='Стойка правая', length=584, width=400, cnt=2), | |
""" | |
new_list = [] | |
keys = list(getattr(x, key) for x in iterable) | |
dist_keys = list(OrderedDict.fromkeys(keys)) | |
for i in dist_keys: | |
items = list(filter(lambda x: getattr(x, key) == i, iterable)) | |
cnt = sum(getattr(x, sum_field) for x in items) | |
new_list.append(items[0]._replace(**{sum_field: cnt})) | |
return new_list | |
keys = ('cpos', 'name', 'length', 'width', 'cnt') | |
Pans = namedtuple('Pans', keys) | |
lp = [Pans(1, 'one', 300, 200, 1), | |
Pans(2, 'tow', 200, 200, 2), | |
Pans(2, 'three', 100, 200, 3), | |
Pans(3, 'for', 200, 200, 1) | |
] | |
pprint(lp) | |
print('') | |
pprint(group_by_key(lp, 'cpos', 'cnt')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment