0

I have a list of points positions, as tuples, and I'm trying to collect the points before and after point N.

points = [
    (0, 0),
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
]

Eg. If I have point three (3, 3) as an input the expected output is [(2,2), (4,4)].

Testing this out, it works fine:

index = 3
a, n, b = points[ index-1 : index+2 ]
print(a, b)
# Returns: (2, 2) (4, 4)

As long as the index is not less than 2 or greater than 5 it works as expected.

Here follows a few examples of where the list of tuples acts as expected:

# Tuple at index zero
print(points[0])
# Returns: (0, 0)
# Tuples from index zero to (but not including) index three
print(points[0:3])
# Returns: [(0, 0), (1, 1), (2, 2)]
# Tuple at index negative one, (6,6) in this case
print(points[-1])
# Returns: (6, 6)

However, when I combine the negative and positive indices it falls apart, why?

# Tuples from index negative one, up to but not including index two
print(points[-1:2])
# Returns: []

The expected output is [(6, 6), (0, 0), (1, 1)] while python gives [].

Solution

Thanks to Dev Khadka.

points = [
    (0,0),
    (1,1),
    (2,2),
    (3,3),
    (4,4),
    (5,5),
    (6,6),
]

index = 0
a, _, b = np.roll(points, -(index-1), axis=0)[:3]
sel_points = zip(a,b)
print(list(zip(*sel_points)))

Result: [(6, 6), (1, 1)]

  • Hi Elias, do you have problems understanding the notation, or are you looking just for a solution? There are few other post that explains the notation. The best way, in my opinion, to read the notation is the following `[len(points)-1:2:1]`. So as len(points)-1 > 2 the result is the empty list. – Dani Mesejo Oct 19 '19 at 17:31
  • For info by definition there is nothing farther than element "-1"... But you might fix that manually – B. Go Oct 19 '19 at 17:37
  • @DanielMesejo I'm looking for a solution, the links provided has clarified a few things about the notation and how slicing works. – Elias Ericsson Rydberg Oct 19 '19 at 17:52

1 Answers1

0

this points[-1:2] is equivalent to points[-1:2:1] which mean you are trying start you index at last element and get to index 2 by going 1 ahead step each time. This indexing will work if you put the step -1 points[-1:2:-1] but this is not what you wanted. You can achive what you want using roll method like below

points = [
    (0, 0),
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
]

indx = 3
a,_,b = np.roll(points, -(indx-1), axis=0)[:3]
a,b
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33
  • This is very close to what I'm after, but the result here is `[2 2] [4 4]` instead of `[(2, 2), (4, 4)]`. I was however able to build on your solution to put it in order. I'll edit my post and mark this as a the solution. – Elias Ericsson Rydberg Oct 19 '19 at 18:07