language design question
Bruno Desthuilliers
onurb at xiludom.gro
Mon Jul 10 05:00:18 EDT 2006
Steven Bethard wrote:
> Terry Reedy wrote:
>
>> "Gregory Guthrie" <guthrie at mum.edu> wrote in message
>> news:1152465029_31209 at sp6iad.superfeed.net...
>>
>>> - why is len() not a member function of strings? Instead one says
>>> len(w).
>>
>>
>> Consider
>>
>>>>> map(len, ('abc', (1,2,3), [1,2], {1:2}))
>>
>> [3, 3, 2, 1]
>>
>> Now try to rewrite this using methods (member functions).
>
map(lambda obj: obj.__len__(), ('abc', (1,2,3), [1,2], {1:2}))
> For all the doubters out there, here's an example you can't really
> rewrite with a list comprehension::
>
> >>> sorted(['aaa', 'bb', 'c'])
> ['aaa', 'bb', 'c']
> >>> sorted(['aaa', 'bb', 'c'], key=len)
> ['c', 'bb', 'aaa']
Nope, but it still doesn't require len() being a function
> If len() were a method of string objects, you could try using the
> unbound method and writing this as::
>
> >>> sorted(['aaa', 'bb', 'c'], key=str.len)
> ['c', 'bb', 'aaa']
>
> But then your code would break on lists that weren't strings.
sorted(['aaa', 'bb', 'c'], key=lambda obj: obj.__len__())
Note that in both cases, my lambda is mostly a reimplementation of len()
- and as far as I'm concerned, len() is quite ok...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list