Assign values from list to list of instances

Dave Angel d at davea.name
Tue Nov 1 11:31:38 EDT 2011


On 11/01/2011 11:05 AM, Gnarlodious wrote:
> I want to assign a list of variables:
> locus=[-2, 21, -10, 2, 12, -11, 0, 3]
>
> updating a list of objects each value to its respective instance:
>
> for order in range(len(Orders)):
> 	Orders[order].locus=locus[order]
>
> This works, even though it reads like doggerel. Is there a more
> pythonesque way using map or comprehension?
>
> -- Gnarlie


You can do that with the enumerate function, or with zip
          for index, instance in enumerate(Orders):
                instance.locus = locus[index]

          for instance, place  in zip(Orders, locus):
                instance.locus = locus[index]

It would be clearer if you used singular for individual items, and 
plural for the collections,

loci  [-2, 21, ....
orders = [list of order objects ...]

for order, locus in zip(orders, loci):
       order.locus = locus


-- 

DaveA




More information about the Python-list mailing list