bob_cobb bob_cobb - 3 months ago 6
Python Question

Generating new list of grouped items within a set

I'm trying to figure out how to convert the following:

results = [(516L, u'dupe', u'dupe', 106L), (517L, u'dupe', u'dupe', 106L), (518L, u'testing', u'testing', 106L), (519L, u'testing', u'testing', 106L), (523L, u'duplicate', u'duplicate', 88L), (524L, u'duplicate', u'duplicate', 88L)]


into a new list like this:

results = [
[(516L, u'dupe', u'dupe', 106L), (517L, u'dupe', u'dupe', 106L)],
[(518L, u'testing', u'testing', 106L), (519L, u'testing', u'testing', 106L)],
[(523L, u'duplicate', u'duplicate', 88L), (524L, u'duplicate', u'duplicate', 88L)]
]


In that they are all grouped by the 3rd index within the set.

I tried something like this:

[list(v) for k,v in groupby(results[3])]


but that returns the 3rd item, and not the 3rd index. Is groupby the right thing to be using here?

Answer

Almost there!

[list(v) for k,v in groupby(results, key=lambda x: x[2])]
                                  #  ^ grouping key  ^ 0-based index

Output:

[(516L, u'dupe', u'dupe', 106L), (517L, u'dupe', u'dupe', 106L)], [(518L, u'testing', u'testing', 106L), (519L, u'testing', u'testing', 106L)], [(523L, u'duplicate', u'duplicate', 88L), (524L, u'duplicate', u'duplicate', 88L)]]

If you do not want a lambda, then from operator import itemgetter and then pass in key=itemgetter(2).

Comments