"for" cycle with assigning index

Carl Banks pavlovevidence at gmail.com
Sat Aug 15 09:39:59 CEST 2009


On Aug 15, 12:17 am, dmitrey <dmitrey.kros... at scipy.org> wrote:
> Hi all,
> could you inform me how to do it properly?
>
> I have the cycle
>
> for i in xrange(len(Funcs2)): # Funcs2 is Python dict
>      Funcs.append(lambda *args, **kwargs: (Funcs2[i](*args, **kwargs)
> [IndDict[left_arr_indexes[i]]]))
>
> So, all the Funcs are initialized with i = last index = len(Funcs2)
>
> When I involve
>
> for i in xrange(len(Funcs2)):
>      Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args,
> **kwargs)[IndDict[left_arr_indexes[i]]]))
>
> I get "list indices must be integers, not dict" (and i is equal to
> Python dictionary, that is Funcs2)
>
> So, how to do it correctly?
> Thank you in advance, D.


Define a helper function to do it:

def create_funcs_caller(i):
    def func(*args,**kwargs):
        return(Funcs2[i](*args,**kwargs)[IndDict[left_arr_indexes
[i]]]))
    retirm func

for i in xrange(len(Funcs2)):
    Funcs.append(create_funcs_caller(i))


(I prefer to do it this way in any case; never liked the keyword
argument hack way of doing it.)


Carl Banks



More information about the Python-list mailing list