开发者

Why doesn't negative values for the second index in a jagged array work in Python?

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

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 does s[1:][:-1] give me the same thing as s[1:] instead of (what I want) [s[i][:-1] for i in range(1,len(s))]. In other words, why does Python ignore my开发者_如何学编程 second index?


Python doesn't have 2-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 you want is:

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


You're misdescribing the results: s[1:][:-1] is definitely not the same as s[:1], as you erroneously say -- it is, rather, the same as s[1:-1]. Check it out!

This must necessarily hold true of any list s, no matter what its contents may be (other lists, dicts, strings, floats, unicorns, ...): s[1:] means "all but the first", then [:-1] means "all but the last", so obviously their combined effects are the same as [1:-1] which means "all but the first and last". The indexing-like syntax with a colon in the brackets is also known as slicing, and when applied to a list (of whatevers) it returns another (typically shorter) list (also of whatevers).

Thinking of s as a "jagged array" rather than what it actually is (just a list, whose items happen to also be lists -- but the type of some or all of the items obviously can't and shouldn't affect the semantics of operations on the list itself, like slicing) may be what's throwing you off; perhaps because, if the first indexing is actually an indexing and not a slicing, its results is an item of the original list -- a "whatever" (a list of ints in your case), not a list of whatevers. So if you then apply a further indexing or slicing you're doing that on one of the original sublists -- a very different matter.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜