Keithx
Keithx

Reputation: 3148

Splitting arrays in Python

I have the following problem: I would like to find different "cuts" of the array into two different arrays by adding one element each time, for example:

If I have an array

a = [0,1,2,3]

The following splits are desired:

[0] [1,2,3]

[0,1] [2,3]

[0,1,2] [3]

In the past I had easier tasks so np.split() function was quite enough for me. How should I act in this particular case?

Many thanks in advance and apologies if this question was asked before.

Upvotes: 0

Views: 38

Answers (2)

Adrian Kurzeja
Adrian Kurzeja

Reputation: 833

Check this out:

a = [0,1,2,3]

result = [(a[:x], a[x:]) for x in range(1, len(a))]

print(result)
# [([0], [1, 2, 3]), ([0, 1], [2, 3]), ([0, 1, 2], [3])]

# you can access result like normal list
print(result[0])
# ([0], [1, 2, 3])

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24049

Use slicing, more details : Understanding slicing.

a = [0,1,2,3]

for i in range(len(a)-1):
    print(a[:i+1], a[i+1:])

Output:

[0] [1, 2, 3]
[0, 1] [2, 3]
[0, 1, 2] [3]

Upvotes: 2

Related Questions