Reputation: 383
I've managed to group first element into a list if they have the same second element using the code below. Is there a better way of doing it.
Note: There's always two same second element.
lst = [
[1, '200309060143'],
[2, '200309060143'],
[3, '200309060143'],
[4, '200309060143'],
[5, '200309060143'],
[6, '200309060143'],
[7, '200309060143'],
[8, '200309060143'],
[1, '200309060144'],
[2, '200309060144'],
[3, '200309060144'],
[1, '200309060145'],
[2, '200309060145'],
[1, '200401100047'],
[2, '200401100047'],
[3, '200401100047']
]
mega_lst = []
temp_lst = []
for i in range(len(lst)):
if i == (len(lst)-1):
break;
else:
if lst[i][1] == lst[i + 1][1]:
temp_lst.append(lst[i][0])
if i == (len(lst)-2):
temp_lst.append(lst[len(lst)-1][0])
mega_lst.append(temp_lst)
else:
temp_lst.append(lst[i][0])
mega_lst.append(temp_lst)
temp_lst = []
print mega_lst
My Codes Result: [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3], [1, 2], [1, 2, 3]]
Desired Result: [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3], [1, 2], [1, 2, 3]]
Upvotes: 0
Views: 862
Reputation: 798456
>>> list(list(x[1]) for x in itertools.groupby(lst, operator.itemgetter(1)))
[[[1, '200309060143'], [2, '200309060143'], [3, '200309060143'], [4, '200309060143'], [5, '200309060143'], [6, '200309060143'], [7, '200309060143'], [8, '200309060143']], [[1, '200309060144'], [2, '200309060144'], [3, '200309060144']], [[1, '200309060145'], [2, '200309060145']], [[1, '200401100047'], [2, '200401100047'], [3, '200401100047']]]
EDIT:
And in case the next step is giving you trouble:
>>> list([y[0] for y in x[1]] for x in itertools.groupby(lst, operator.itemgetter(1)))
[[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3], [1, 2], [1, 2, 3]]
Upvotes: 2