String building using join

Kushal Kumaran kushal.kumaran+python at gmail.com
Mon Jan 3 22:52:53 EST 2011


On Mon, Jan 3, 2011 at 3:07 AM, gervaz <gervaz at gmail.com> wrote:
> On 2 Gen, 19:14, Emile van Sebille <em... at fenx.com> wrote:
>> <snip>
>>
>> class Test:
>>       def __init__(self, v1, v2):
>>           self.v1 = v1
>>           self.v2 = v2
>>
>> t1 = Test("hello", None)
>> t2 = Test(None, "ciao")
>> t3 = Test("salut", "hallo")
>> t = [t1, t2, t3]
>>
>> "\n".join([y for x in t for y in [x.v1,x.v2] if y])
>>
>>
>>
> <snip>
>
> Thanks Emile, despite that now the solution runs in quadratic time I
> guess. I could also provide a __str__(self) representation, but in my
> real code I don't have access to the class. Also using str() on an
> empty object (i.e. None), the representation is 'None'.
>

Since no one else has mentioned it, I'll just point out that Emile's
solution does not run in quadratic time.  It has the same number of
operations as the originally posted code.

That str(None) results in "None" is not a problem because of the "if
y" test in the list comprehension.

-- 
regards,
kushal



More information about the Python-list mailing list