Why do negative values ​​for the second index in a jagged array work in Python?

For example, if I have the following (Project Euler data):

s = [[75],
     [95, 64],
     [17, 47, 82],
     [18, 35, 87, 10],
     [20, 4, 82, 47, 65],
     [19, 1, 23, 75, 3, 34],
     [88, 2, 77, 73, 7, 63, 67],
     [99, 65, 4, 28, 6, 16, 70, 92],
     [41, 41, 26, 56, 83, 40, 80, 70, 33],
     [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
     [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
     [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
     [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
     [63, 66, 4, 68,89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
     [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]

      

Why s[1:][:-1]

gives me the same thing s[1:]

instead of (which I need) [s[i][:-1] for i in range(1,len(s))]

. In other words, why is Python ignoring my second index?

+2


a source to share


2 answers


Python doesn't have two dimensional lists, it has lists of lists. I think the first [1:] gives everything but the first contained list, and the second [: -1] takes that result and removes the last contained list.

What would you like:



[r[:-1] for r in s[1:]]

      

+3


a source


You are describing the results incorrectly: s[1:][:-1]

definitely not as much s[:1]

as you mistakenly say, it is rather the same as s[1:-1]

. Check it!

This must be true for any list s

, regardless of its content (other lists, voice recorders, strings, floats, unicorns, ...): s[1:]

means "everything but the first", it [:-1]

means "everything but the last", so obviously , their combined effects are the same as [1:-1]

, which means "everything except the first and the last". An index-like syntax with a colon in parentheses is also known as a slice, and when applied to a list (whatevers) it returns a different (usually shorter) list (also from whatevers).



Thinking s

as a "jagged array" rather than what it really is(just a list whose elements are also lists, but the type of some or all of the elements obviously cannot and should not affect the semantics of operations in the list itself, like slicing) might be what throws you off; perhaps because if the first indexing is actually indexing and not slicing, its result is an element of the original list - "all" (a list of integers in your case), not a list of whatevers. Therefore, if you then apply further indexing or slicing, you do so in one of the original subscriptions - a completely different matter.

@Mark's answer already showed a canonical solution for list comprehension to do what you actually want. I think other approaches, if you have matlab code and want a Python equivalent, might include OMPC (but I haven't tried it myself).

+2


a source







All Articles