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

Emile van Sebille emile at fenx.com
Thu Sep 20 17:00:16 CEST 2012


On 9/20/2012 7:41 AM Ara Kooser said...
> 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.

So, say the desired COUNT is 50, you could do:

ants = zip(
     [ Ant("Red_%s" % c ,"Red","yellow_food") for c in range(COUNT) ],
     [ Ant("Yellow_%s" % c ,"Yellow","red_food") for c in range(COUNT) ])

Emile




More information about the Tutor mailing list