consider the following list:
alist = [[1, 'AAA0'], [2, 'AAAA1'], [3, 'BB2BB2'], [4, 'A3A3'], [5, 'A3A3']]
then if I want to sort the list according to the 2nd slot but at the same time get only the items that have ‘A’ inside I use:
from operator import itemgetter
print str([pt for pt in sorted(alist, key=itemgetter(1)) if 'A' in pt[1]])
my question is how after sorting them alphabetically, how do I group them by string length first and then group the ones that are the same. Like being able to retrieve the 2 ‘A3A3’ only.
the
if 'A' in pt[1]
is returning all items that contain ‘A’ not the ones with 1 ‘A’.
so how do I group those with 1 ‘A’, those with 2 ‘A’ etc?
You can group elements of an iterable by custom key function with
itertools.groupby: