Как перебрать таблицу и сохранить список для каждой группы для последовательного анализа? - PullRequest
0 голосов
/ 05 января 2020

Мне нужна программа, чтобы возвратить список списков, в которых списки являются действиями каждого человека, то есть сгруппированы по лицам - начиная с таблицы столбцов персонажа и действия.

Например, проверка столбца ['1', '1', '2'] и столбца активности ['a', 'b', 'a'] должны вернуть [['a', 'b'], ['a'] ], поскольку у человека «1» есть действия «a» и «b», а у человека «2» - «a».

Цель состоит в том, чтобы проанализировать последовательности или потоки действий.

Я попробовал следующее:

#having a table with columns person, activity and day, stored in lists:
person=['1','2','2','2','3','3']
activity=['a','b','c','d','b','c']

#starting with an empty list to store the lists
list_of_lists=[]

#starting with an empty current list
current_list=[]

#iterating each row
for i in range(len(person)):

#if the list of list is empty (in the beginning)
    if len(list_of_lists)==0:

#append the i'th activity in current list
        current_list.append(activity[i])

#otherwise if the i'th person is the same as the latter, append to the same list
    elif person[i]==person[i-1]:
        current_list.append(activity[i])

#otherwise (if it iterates over a a new person) store the current list and create a new list
    else:
        list_of_lists.append(current_list)
        current_list=list()

Ответы [ 4 ]

0 голосов
/ 05 января 2020
from itertools import groupby, islice


people = ["1", "2", "2", "2", "3", "3"]
activities = ["a", "b", "c", "d", "b", "c"]

activities_iter = iter(activities)

activity_groups = [list(islice(activities_iter, len(list(group)))) for _, group in groupby(people)]
print(activity_groups)

Выход:

[['a'], ['b', 'c', 'd'], ['b', 'c']]
0 голосов
/ 05 января 2020

Эффективный способ группировки между итерациями - itertools.groupby.

from itertools import groupby
from operator import itemgetter

first = itemgetter(0)
second = itemgetter(1)

pairs = sorted(zip(person, activity), key=first)  # data must be sorted prior to groupby

[list(map(second, v)) for _, v in groupby(pairs, key=first)]

[['a'], ['b', 'c', 'd'], ['b', 'c']]
0 голосов
/ 05 января 2020

Как говорит @Scott Hunter list_of_lists начинается пусто и остается пустым. Еще одна проблема с вашим кодом заключается в том, что окончательный current_list будет добавлен к list_of_lists. Вы можете изменить свой код следующим образом:

persons = ['1','2','2','2','3','3']
activities = ['a','b','c','d','b','c']
list_of_lists = []
current_list = []
for i in range(len(persons)):
    if i==0:  # use i == 0 instead of len(list_of_lists)==0 as the starting condition
        current_list.append(activities[i])
    elif persons[i]==persons[i-1]:
        current_list.append(activities[i])
    else:
        list_of_lists.append(current_list)
        current_list=[activities[i]]   # remember to add the current activity here
if current_list:     # after loop has finished still need to add the current list
    list_of_lists.append(current_list)

Это можно значительно упростить, используя zip и «отстающую» версию списка person.

result = []
for person, previous, activity in zip(persons, [None] + persons, activities):
    if person == previous:
        result[-1].append(activity)
    else:
        result.append([activity])
0 голосов
/ 05 января 2020

list_of_lists начинается пустым; поскольку в этом случае он не изменяется, он никогда не изменяется, поэтому в конце он пуст. (Ничто не перезаписывается).

...