Misuse of list comprehensions?

duncan smith buzzard at urubu.freeserve.co.uk
Fri May 23 10:25:39 EDT 2008


Simon Forman wrote:
> On May 21, 4:36 am, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
>> Simon Forman a écrit :
>>
>>
>>
>>> On May 20, 8:58 am, Paul McGuire <pt... at austin.rr.com> wrote:
>>>> On May 20, 10:50 am, s0s... at gmail.com wrote:
>>>>> You don't need all those conditionals. A set differs from a list
>>>>> precisely in the fact that each element is unique. And since the
>>>>> function is expecting "s" to be an iterable object, it can be
>>>>> constructed even without a for loop:
>>>>> def compress(s):
>>>>>     return list(set(s))
>>>>> That does the trick.
>>>> Only if order does not need to be maintained.  list(set(s)) will not
>>>> necessarily keep the unique characters in the order they are seen.
>>>> We'll have to check with the OP to see if this is important (I just
>>>> assumed that it was because of the use of list comps).
>>>> -- Paul
>>> If order is important, you can use sorted() instead of list() like so:
>>> def compress(s):
>>>     new = sorted(set(s), key=s.index)
>>>     return return ''.join(new)
>> This won't still preserve the *original* order.
> 
> 
> I don't understand.
> 
> new will contain each unique item in s, sorted in order of the items'
> first occurance in s, right?
> There are other ways to do it (other functions that could be passed to
> sorted() as the key arg) of course, but this seems like a good value
> of "original order", no? :)
> 
> Regards,
> ~S

But, I think, worst case quadratic performance through generating all 
the indices.

Duncan



More information about the Python-list mailing list