Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : group elements together in list

I'm currently working with itertools to create and return a list whose elements are lists that contain the consecutive runs of equal elements of the original list.

import itertools
it = [1, 1, 5, 5, 5, 'test', 'test', 5]

new = len(it)
for a in range(new):
  return [list(k) for a, k in itertools.groupby(it)] 

For the above example the result is:

[[1, 1], [5, 5, 5], ['test', 'test'], [5]]

Can I achieve this without using itertools?

like image 548
N997 Avatar asked Oct 28 '25 11:10

N997


1 Answers

You can pair adjacent items by zipping the list with itself but with a padding of float('nan') since it can't be equal to any object, and then iterate through the zipped pairs to append items to last sub-list of the output list, and add a new sub-list when the adjacent items are different:

output = []
for a, b in zip([float('nan')] + it, it):
    if a != b:
        output.append([])
    output[-1].append(b)

output becomes:

[[1, 1], [5, 5, 5], ['test', 'test'], [5]]
like image 52
blhsing Avatar answered Oct 31 '25 02:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!