Python第二组清单 [英] Python group two lists

查看:83
本文介绍了Python第二组清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

             A = ['T', 'D', 'Q', 'D', 'D']
             sessionid = [1, 1, 1, 2, 2]

无论如何,我可以为相同的sessionid将A中的项目分组,这样我就可以打印出以下内容:

Is there anyway i could group items in A for the same sessionid, so that i could print out the following:

              1: ["T", "D","Q"]
              2: ["D","D"]

推荐答案

itertools

The itertools groupby function is designed to do this sort of thing. Some of the other answers here create a dictionary, which is very sensible, but if you don't actually want a dict then you can do this:

from itertools import groupby
from operator import itemgetter

A = ['T', 'D', 'Q', 'D', 'D']
sessionid = [1, 1, 1, 2, 2]    

for k, g in groupby(zip(sessionid, A), itemgetter(0)):
    print('{}: {}'.format(k, list(list(zip(*g))[1])))

输出

1: ['T', 'D', 'Q']
2: ['D', 'D']

operator.itemgetter(0) 返回获取该项目的可调用对象传递给它的任何对象的索引为0; groupby将此作为关键功能来确定可以将哪些项目分组在一起.

operator.itemgetter(0) returns a callable that fetches the item at index 0 of whatever object you pass it; groupby uses this as the key function to determine what items can be grouped together.

请注意,此解决方案和类似解决方案均假定对sessionid索引进行了排序.如果不是,那么在将它们传递给groupby之前,您需要使用相同的键函数对zip(sessionid, A)返回的元组列表进行排序.

Note that this and similar solutions assume that the sessionid indices are sorted. If they aren't then you need to sort the list of tuples returned by zip(sessionid, A) with the same key function before passing them to groupby.

已编辑以在Python 2和Python 3上正常工作

edited to work correctly on Python 2 and Python 3

这篇关于Python第二组清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆