Home > OS >  Separating elements in a list but still in order another list
Separating elements in a list but still in order another list

Time:11-05

I want to separate this list

[1000011]

and turn it into

["1", "0000", "11"]

CodePudding user response:

itertools has a groupby() method, which should do exactly what you want.

from itertools import groupby

vals = [1000011]
splitVals = []

for val in vals:
    splitVals.extend(''.join(g) for k,g in groupby(str(val)))

print(splitVals)

Or, if you want you can compress the for loop into one line:

splitVals = [''.join(g) for val in vals for k,g in groupby(str(val))]

Demo: Try it online!

CodePudding user response:

You can use itertools.groupby:

l = [1000011]

from itertools import groupby

[[''.join(g) for k,g in groupby(str(x))] for x in l]

output: ['1', '0000', '11']

If you have several values in the input list:

input: l = [1000011, 1221]

output: [['1', '0000', '11'], ['1', '22', '1']]

  • Related