Метод groupby

Введение

Примеры

Пример 2

Этот пример иллюстрирует, как выбран ключ по умолчанию, если мы не указываем

 c = groupby(['goat', 'dog', 'cow', 1, 1, 2, 3, 11, 10,('persons', 'man', 'woman')])
dic = {}
for k, v in c:
    dic[k] = list(v)
dic

 

Результаты в

 {1: [1, 1],
 2: [2],
 3: [3],
('persons', 'man', 'woman'): [('persons', 'man', 'woman')],
 'cow': ['cow'],
 'dog': ['dog'],
 10: [10],
 11: [11],
 'goat': ['goat']}

 

Обратите внимание, что кортеж в целом считается одним ключом в этом списке

Пример 3

Обратите внимание, что в нашем примере мулато и верблюд не отображаются в нашем результате. Отображается только последний элемент с указанным ключом. Последний результат для c фактически уничтожает два предыдущих результата. Но посмотрите новую версию, в которой данные отсортированы первыми по тому же ключу.

 list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat',('persons', 'man', 'woman'), \
               'wombat', 'mongoose', 'malloo', 'camel']
c = groupby(list_things, key=lambda x: x[0])
dic = {}
for k, v in c:
    dic[k] = list(v)
dic

 

Результаты в

 {'c': ['camel'],
 'd': ['dog', 'donkey'],
 'g': ['goat'],
 'm': ['mongoose', 'malloo'],
 'persons': [('persons', 'man', 'woman')],
 'w': ['wombat']}

 

Сортированная версия

 list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat',('persons', 'man', 'woman'), \
               'wombat', 'mongoose', 'malloo', 'camel']
sorted_list = sorted(list_things, key = lambda x: x[0])
print(sorted_list)
print()
c = groupby(sorted_list, key=lambda x: x[0])
dic = {}
for k, v in c:
    dic[k] = list(v)
dic

 

Результаты в

 ['cow', 'cat', 'camel', 'dog', 'donkey', 'goat', 'mulato', 'mongoose', 'malloo',('persons', 'man', 'woman'), 'wombat']

{'c': ['cow', 'cat', 'camel'],
 'd': ['dog', 'donkey'],
 'g': ['goat'],
 'm': ['mulato', 'mongoose', 'malloo'],
 'persons': [('persons', 'man', 'woman')],
 'w': ['wombat']} 

Пример 4

В этом примере мы видим, что происходит, когда мы используем разные типы итераций.

 things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "harley"), \
          ("vehicle", "speed boat"), ("vehicle", "school bus")]
dic = {}
f = lambda x: x[0]
for key, group in groupby(sorted(things, key=f), f):
    dic[key] = list(group)
dic

 

Результаты в

 {'animal': [('animal', 'bear'),('animal', 'duck')],
 'plant': [('plant', 'cactus')],
 'vehicle': [('vehicle', 'harley'),
 ('vehicle', 'speed boat'),
 ('vehicle', 'school bus')]}


 

Этот пример ниже по сути такой же, как и над ним. Разница лишь в том, что я изменил все кортежи на списки.

 things = [["animal", "bear"], ["animal", "duck"], ["vehicle", "harley"], ["plant", "cactus"], \
          ["vehicle", "speed boat"], ["vehicle", "school bus"]]
dic = {}
f = lambda x: x[0]
for key, group in groupby(sorted(things, key=f), f):
    dic[key] = list(group)
dic

 

Результаты

 {'animal': [['animal', 'bear'], ['animal', 'duck']],
 'plant': [['plant', 'cactus']],
 'vehicle': [['vehicle', 'harley'],
  ['vehicle', 'speed boat'],
  ['vehicle', 'school bus']]} 

Синтаксис

Параметры

Примечания