1

Is there a default python function to be able to separate group of numbers without using a conventional loop?

inputArray=["slide_0000_00.jpg", "slide_0000_01.jpg","slide_0000_02.jpg","slide_0001_01.jpg","slide_0001_02.jpg","slide_0002_01.jpg"]

resultArray=[["slide_0000_01.jpg", "slide_0000_02.jpg", "slide_0000_03.jpg"],["slide_0001_01.jpg", "slide_0001_02.jpg"], ["slide_0002_01.jpg"]]
Nazim Moises
  • 47
  • 1
  • 7
  • I think you're looking for a list comprehension with a regex, or perhaps a `groupby` operation. Please note that you are separating string by an included slice, not "numbers". – Prune Mar 23 '20 at 21:00
  • Consider [natural sorting](https://stackoverflow.com/a/4836734/355230) the input list. – martineau Mar 23 '20 at 22:03

1 Answers1

4

use itertools.groupby to group consecutive items by middle part:

inputArray=["slide_0000_00.jpg",
 "slide_0000_01.jpg",
 "slide_0000_02.jpg",
 "slide_0001_01.jpg",
 "slide_0001_02.jpg",
 "slide_0002_01.jpg"]

import itertools

result = [list(g) for _,g in itertools.groupby(inputArray,key = lambda x:x.split("_")[1])]

which gives:

>>> result
[['slide_0000_00.jpg', 'slide_0000_01.jpg', 'slide_0000_02.jpg'],
 ['slide_0001_01.jpg', 'slide_0001_02.jpg'],
 ['slide_0002_01.jpg']]

note that if the groups don't follow, the grouping won't work (unless you sort the list first, here simple sort would work but the complexity isn't satisfactory). A classic alternative in that case is to use collections.defaultdict(list):

import collections

d = collections.defaultdict(list)

for x in inputArray:
    d[x.split("_")[1]].append(x)

result = list(d.values())

the result is identical (order can vary, depending on the version of python and if dictionaries preserve order. You can expect that property from version 3.5)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thanks for your edit. Itertools works, but the result with a messy input gives an unexpected result just like you said. I would have liked to understand how you would have used collections for a case like this. Thank you! – Nazim Moises Mar 23 '20 at 22:17
  • your really rocks, thanx! – Nazim Moises Mar 23 '20 at 23:09