Home > Software engineering >  Splitting arrays in Python
Splitting arrays in Python

Time:11-26

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.

CodePudding user response:

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]

CodePudding user response:

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])
  • Related