Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #43866

Re: Strange behavior for a 2D list

References <CAJq7yh4Pc=Ge=AU=XDKQtpy3PLM-SYetBN2u+9V8PmY3B+RV2Q@mail.gmail.com> <loom.20130418T230521-87@post.gmane.org>
Date 2013-04-18 15:33 -0600
Subject Re: Strange behavior for a 2D list
From "Wim R. Cardoen" <wcardoen@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.800.1366320798.3114.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

Thank you all for your replies.
I had the matrix concept in mind such as
explained in the numpy example.

Rob



On Thu, Apr 18, 2013 at 3:19 PM, Wolfgang Maier <
wolfgang.maier@biologie.uni-freiburg.de> wrote:

> Robrecht W. Uyttenhove <ruyttenhove <at> gmail.com> writes:
>
> >
> > Hello,
> > I tried out the following
> code:y=[range(0,7),range(7,14),range(14,21),range(21,28),range(28,35)]
> > >>> y[[0, 1, 2, 3, 4, 5, 6],  [7, 8, 9, 10, 11, 12, 13],
> >       [14, 15, 16, 17, 18, 19, 20],  [21, 22, 23, 24, 25, 26, 27],  [28,
> >
>        29, 30, 31, 32, 33, 34]]
> > >>> y[1:5:2][::3]
> > [[7, 8, 9, 10, 11, 12, 13]]
> > I expected the 2D list:[[ 7, 10, 13],
> >  [21, 24, 27]]
> >
> > Any ideas?
> >
> > Thanks,
> > Rob
> > PS: I used Python 2.7.3
> >
>
> The explanation is rather simple, just break up your complex slicing into
> its parts:
> y[1:5:2] => [[7, 8, 9, 10, 11, 12, 13],[21, 22, 23, 24, 25, 26, 27]]
> and [::3] is asking for the first,4th,7th,... element from this list.
> Obviously, only the first one's existing, so [7, 8, 9, 10, 11, 12, 13]
>
> What you expected is kind of vertical slicing through the rows. I don't
> think you can achieve this with slicing alone in standard Python, but it's
> possible with numpy arrays.
> In Python you will have to combine slicing with a comprehension, like this:
> [x[::3] for x in y[1:5:2]]
>
> Best,
> Wolfgang
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
---------------------------------------------------------------
Wim R. Cardoen, PhD
Staff Scientist,
Center for High Performance Computing
University of Utah
(801)971-4184

*μὴ μου τοὺς κύκλους τάραττε! (Ἀρχιμήδης)*
---------------------------------------------------------------

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Strange behavior for a 2D list "Wim R. Cardoen" <wcardoen@gmail.com> - 2013-04-18 15:33 -0600

csiph-web