[Tutor] Populating a list with object to be called by a class

Ara Kooser ghashsnaga at gmail.com
Thu Sep 20 17:08:16 CEST 2012


Oscar,

  Thanks for that. I feel a bit silly. I forgot about the % which was
hanging me up. I am trying to be a better coder. More work ahead for me!

ara

On Thu, Sep 20, 2012 at 9:01 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> On 20 September 2012 15:41, Ara Kooser <ghashsnaga at gmail.com> wrote:
>
>> Morning,
>>
>>   I dug out some old code from 5 years ago to clean up and get in working
>> order. It's a simple agent based model. I have class called Ant which
>> contains all the ant-like functions.
>>
>> I have a list that tracks the ants but I did this is a very crude way. I
>> basically copied and pasted everything in there like this:
>>
>> ants =
>> [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"),
>>
>> Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"),
>>
>> Ant("Red_3","Red","yellow_food"),Ant("Yellow_3","Yellow","red_food"),
>>
>> Ant("Red_4","Red","yellow_food"),Ant("Yellow_4","Yellow","red_food"),
>>           .......]
>>
>> I couldn't figure out how to populate the list from a user input. Say if
>> the user wanted 50 Red and 50 Yellow ants. So it's hardcoded at 500 which
>> is not an elegant solution.
>>
>> I went back to work on this over the past couple of days but still can't
>> figure out how to populate the list so I end up with Red_1 then Red_2 etc...
>>
>> What would be a good python way to do this?
>>
>
> How about this:
>
> numants = 500
>
> ants = []
> for i in range(1, numants+1):
>     ants.append(Ant('red_%i' % i, 'Red', 'yellow_food'))
>     ants.append(Ant('yellow_%i' % i, 'Yellow', 'red_food'))
>
> Oscar
>



-- 
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an
sub cardine glacialis ursae.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120920/036a515b/attachment.html>


More information about the Tutor mailing list