Is there a better way of doing this?

Lie Ryan lie.1296 at gmail.com
Sat Mar 7 07:11:22 EST 2009


mattia wrote:
> Il Sat, 07 Mar 2009 00:05:53 -0200, Gabriel Genellina ha scritto:
> 
>> En Fri, 06 Mar 2009 21:31:01 -0200, mattia <gervaz at gmail.com> escribió:
>>
>>> Thanks, I've found another solution here:
>>> http://www.obitko.com/tutorials/
>>> genetic-algorithms/selection.php
>>> so here is my implementation:
>>>
>>>
>>> def get_fap(fitness, population):
>>>     fap = []
>>>     total = 0
>>>     for x in population:
>>>         f = fitness(x)
>>>         fap += [(f, x)]
>>>         total += f
>>>     return sorted(fap, reverse=True), total
>> Imagine you're working with someone side by side. You write a note in a
>> piece of paper, put it into an envelope, and hand it to your co-worker.
>> He opens the envelope, throws it away, takes the note and files it
>> inside a folder right at the end. And you do this over and over. What's
>> wrong in this story?
>>
>> Please save our trees! Don't waste so many envelopes - that's just what
>> this line does:
>>
>>           fap += [(f, x)]
>>
>> Environmentally friendly Pythoneers avoid using discardable intermediate
>> envelopes:
>>
>>           fap.append((f, x))
>>
>> Please recycle!
> 
> Yes, sorry, I have to recycle! But how about this:
>>>> rw = [[2,4], [4,5,6],[5,5]]
>>>> rw += [[1,1]]*2
>>>> rw
> [[2, 4], [4, 5, 6], [5, 5], [1, 1], [1, 1]]
>>>> rw = [[2,4], [4,5,6],[5,5]]
>>>> rw.append([1,1]*2)
>>>> rw
> [[2, 4], [4, 5, 6], [5, 5], [1, 1, 1, 1]]
>>>> rw = [[2,4], [4,5,6],[5,5]]
>>>> rw.append([[1,1]]*2)
>>>> rw
> [[2, 4], [4, 5, 6], [5, 5], [[1, 1], [1, 1]]]
> How can I recicle in this way using append?

Not .append() but .extend()

 >>> rw = [[2,4], [4,5,6],[5,5]]
 >>> rw.extend([[1,1]]*2)
 >>> rw
 > [[2, 4], [4, 5, 6], [5, 5], [1, 1], [1, 1]]



More information about the Python-list mailing list