Don Quixote Don Quixote - 1 year ago 76
Python Question

Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list

Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numbers of indices.

'ABCDE', list_of_configurations

['A', 'BCDE']
['AB', 'CDE']
['A', 'B', 'C', 'D', 'E']

Final note, I want it be dynamic in that it can apply to a string of 5 characters or a string of 9 characters. I was trying to figure this out but I think it is beyond my current skill level.

Answer Source

If you want to apply that configuration list of lists containing possible "slices" of a string, here is a way to do it - basically, we take a slice and pass the rest of the string to the next step:

s = 'ABCDE'
c = [[5], [4, 1], [3, 2], [1, 1, 1, 1, 1]]

for item in c:
    result = []
    s_copy = s
    for index in item:
        s_copy = s_copy[index:]


['ABCD', 'E']
['ABC', 'DE']
['A', 'B', 'C', 'D', 'E']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download