slicing lists

castironpi at gmail.com castironpi at gmail.com
Wed May 7 20:22:31 EDT 2008


On May 7, 6:58 pm, Ivan Illarionov <ivan.illario... at gmail.com> wrote:
> On Wed, 07 May 2008 23:46:33 +0000, Ivan Illarionov wrote:
> > On Wed, 07 May 2008 23:29:27 +0000, Yves Dorfsman wrote:
>
> >> Is there a way to do:
> >> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> >> x[0,2:6]
>
> >> That would return:
> >> [0, 3, 4, 5, 6]
>
> > IMHO this notation is confusing.
>
> > What's wrong with:
> > [0]+x[2:6]
>
> >> I am surprised this notation is not supported, it seems intuitive. A
> >> concrete example of the sort of thing I want to do:
>
> >> p = file('/etc/passwd').readlines()
> >> q = [ e.strip().split(':')[0,2:] for e in p ]
>
> >> (getting rid of the password / x field)
>
> > This works and is clearer:
> > [[0] + e.strip().split(':')[2:] for e in open('/etc/passwd')]
>
> or maybe you wanted to do this:
>
> >>> [e.split(':')[0] for e in open('/etc/passwd')]
>
> ['root', 'daemon', 'bin', 'sys', 'sync', ...]
>
> What are you trying to get from /etc/passwd?
>
> --
> Ivan- Hide quoted text -
>
> - Show quoted text -

The t.  Oughtn't there be a run on Guido's name more often than is?

You -could- write:

x[ slice(0)+slice(2,6) ]

where slice would be an 'autochaining' type under a syntax.  Fine for
slices, not for logic.

x[ b1+And+b2+Or+b3 ]

would also register as b1 and b2 or b3, which really quickly rises on
the wheel again, er, um, crawls up the spout.

Would you be happy with x[ '0,2:6' ], necessarily in quotes?  With two
punctuation marks you couldn't get much farther in money than Python
does today.

x[ '0 2:6' ]
-> x.__getitem__( x, '0 2:6' )
-> '0 2:6'.split( )
-> x.__getslice__( x, slice( 0 ) )
... + x.__getslice__( x, slice( 2, 6 ) )

However, it's not clear it's trivial to overwrite a built-in type's
__getitem__!



More information about the Python-list mailing list