1

I have an array:

foo = ['1', '2', '', '1', '2', '3', '', '1', '', '2']

¿Is there any efficient way to split this array into sub-arrays using '' as separator?

I want to get:

foo = [['1', '2'], ['1', '2', '3'], ['1'], ['2']]
1
  • 2
    Your foo looks like a regular list. Are you sure it's a numpy array? Commented Dec 26, 2022 at 22:51

2 Answers 2

5

In one line:

[list(g) for k, g in itertools.groupby(foo, lambda x: x == '') if not k]

Edit:

From the oficial documentation:

groupby

generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function).

The key I generate can be True, or False. It changes each time we find the empty string element. So when it's True, g will contain an iterable with all the element before finding an empty string. So I convert this iterable as a list, and of course I add the group only when the key change

Don't know how to explain it better, sorry :/ Hope it helped

Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain it please?
@renton01 I tried
"add the group only when the key change" you actually add the group only when the key is truthy, i.e. non-empty strings
You could also use ''.__eq__ instead of lambda x: x == ''.
1

Create a list containing a single list.

output = [[]]

Now, iterate over your input list. If the item is not '', append it to the last element of output. If it is, add an empty list to output.

for item in foo:
    if item == '':
        output.append([])
    else:
        output[-1].append(item)

At the end of this, you have your desired output

[['1', '2'], ['1', '2', '3'], ['1'], ['2']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.