Python第二组清单 [英] Python group two lists
问题描述
我有两个列表:
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"]
推荐答案
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屋!