i.e.
more elegant than
[arr[x] for x in [1,6,9] ]
along the lines of
arr[1,6,9]
not a big issue, but i am curious
-- vish
_______________________________________________
Python-il mailing list
Pyth...@hamakor.org.il
http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
Unlike Perl, Python is based upon the principle of having exactly one
way to do each thing.
List comprehension (the [arr[x] for x in [1,6,9] ] method) is one way to
accomplish the goal, and it is reasonably parsimonious. Therefore, it
is very unlikely to have another method of accomplishing the same.
However, if the indices themselves form an arithmetic sequence (such as
[1,5,9]), it is possible to use a slice notation: arr[1:10:4]
--- Omer
--
In a guided tour in Scotland:
'And, what is worn under the kilt?'
'Nothing.'
'Huh?'
'Nothing. It's all in perfectly good working order, thank you.'
My opinions, as expressed in this E-mail message, are mine alone.
They do not represent the official policy of any organization with which
I may be affiliated in any way.
WARNING TO SPAMMERS: at http://www.zak.co.il/spamwarning.html
Unlike Perl, Python is based upon the principle of having exactly oneway to do each thing.
List comprehension (the [arr[x] for x in [1,6,9] ] method) is one way to
accomplish the goal, and it is reasonably parsimonious. Therefore, it
is very unlikely to have another method of accomplishing the same.
Not by default, but if it's important to you, you can make it. One way to do
so: define a class L as a subclass of list, overriding its [] implementation:
class L(list):
def __getitem__(self, idx):
try:
i = iter(idx)
except TypeError:
return super(L, self).__getitem__(idx)
else:
return [self[ii] for ii in i]
With this definition in scope,
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L(arr)[1,6,9]
[1, 6, 9]
and even
>>> L(arr)[1,6,9,[2,3]]
[1, 6, 9, [2, 3]]
Most experienced Python users will frown upon this, though.
--
Alon Levy
Have you tried shedskin recently? it actually works. I mean, realistically, if
he actually ends up with this as a bottleneck, he could try to code it as an
iterator (no in between copy in that case), not sure if it would actually be
faster (depends really):
def slice(self, idx):
for i in idx:
yield self[i]
list(myarr.slice([1,2])) == myarr([1,2])
btw, he can of course have a constructor and slice operator that avoid
the double
parenthesis if you really want (which btw shedskin doesn't support yet ;), so:
def slice(self, *idx):
...
class myarr(list):
def __init__(self, *items):
super(list, self).__init__(items)
list(myarr.slice(1,2)) == myarr(1,2)
actually I think constructing a list and then giving it to the myarr
constructor (by inheritance) shouldn't copy the list. Actually I'm not
sure if it's any different then having a wrapper class.
> Shai.