python - 如何为每个组迭代表和存储列表以进行顺序分析?
问题描述
我需要程序返回一个列表列表,其中列表是每个人的活动,即按人分组 - 从人员和活动列的表开始。
例如,列 ['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()
解决方案
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']]
推荐阅读
- parsing - Haskell 解析:x ++ y : z
- utf-8 - 如何使用 redis-cli 将 utf-8 字符设置为 redis?
- php - 我对带有 html 内容的 mail() 有疑问
- docker - 通过 Oozie 运行 Docker 容器
- python-3.x - python 3.7.4 pip install - NameError: name 'reload' is not defined
- blazor - 如何在 Blazor Server 应用程序的客户端更新服务器端更改?
- node.js - 节点 js 将日期转换为有效的 mssql 日期
- excel - 根据其他三个单元格中的值对单元格的成本求和 - Excel
- android - 如何从异步存储中获取数据并保存在共享首选项 android 本机代码中
- django - 如何在 Django ORM 中按相关模型计数进行分组