bob_cobb - 1 year ago 88
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?

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)`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download