首页 > 解决方案 > 如何为每个组迭代表和存储列表以进行顺序分析?

问题描述

我需要程序返回一个列表列表,其中列表是每个人的活动,即按人分组 - 从人员和活动列的表开始。

例如,列 ['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()

标签: pythonsequential

解决方案


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']]

推荐阅读