Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python group two lists

I have two lists:

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

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"]
like image 672
yingnan liu Avatar asked Dec 07 '22 22:12

yingnan liu


1 Answers

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

output

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

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.

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.


edited to work correctly on Python 2 and Python 3

like image 104
PM 2Ring Avatar answered Dec 10 '22 12:12

PM 2Ring