Is there a better way to chose a slice of a list?
John Machin
sjmachin at lexicon.net
Tue May 19 19:59:47 EDT 2009
On May 20, 7:38 am, walterbyrd <walterb... at iname.com> wrote:
> On May 8, 5:55 pm, John Yeung <gallium.arsen... at gmail.com> wrote:
>
> > On May 8, 3:03 pm,walterbyrd<walterb... at iname.com> wrote:
>
> > > This works, but it seems like there should be a better way.
>
> > > --------------
> > > ---------------
>
> > I think you should provide much more information, primarily why you
> > want to do this. What is the larger goal you are trying to achieve?
>
> I am just looking for a less verbose, more elegant, way to print a
> slice of a list. What is hard to understand about that?
Ummm two things, (1) You didn't say that was what you wanted (2) It's
a nonsense anyway:
Your original statement "choose a slice of alist": answer = alist
[lo:hi]
Your current statement "print a slice of a list" (one element per line
as per your example): can not be done much less verbosely and more
elegantly than:
for x in alist[lo:hi]:
print x
Your real problem appears to be the horrid method of deriving lo and
hi.
You gave ONE example without stating anything more precise than that
it was an example of a slice of a list [which was obvious anyway] and
didn't specify in what sense of "better" you wanted a better way. So
people have to guess what you really want.
Guessing that the 'tue' and 'fri' in your one example will always be
constants, here are two options:
E.g. given
week = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
Option (1):
SUN, MON, TUE, WED, THU, FRI, SAT = range(7)
for day in week[TUE:FRI]:
print day
Option (2):
for day in week[2:5]:
print day
HTH,
John
More information about the Python-list
mailing list