简体   繁体   中英

Group same elements in list python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM