scoping problem with lambda

matt matt at virtualspectator.com
Fri Jun 2 21:16:41 EDT 2000


The following code works in global space(Please note, some \n and extra tabs
inserted for viewing sake),

tmp = [[['a'],['one','two','three','four']],
	[['b'],['one','two','four','five']],
	[['c'],['one','two','three','six']],
	[['d'],['one','two','two','four']],
	[['e'],['one','ten','three','four']]]  

kformat = ['one','two','three','four']

tmp2 = tmp[:]
for i in (0,2,3):
	tmp2 = filter(lambda x:x[1][i] in (kformat[i],),tmp2)

the result is :
>>> tmp2
[[['a'], ['one', 'two', 'three', 'four']], [['e'], ['one', 'ten', 'three', 'four']]]
Which is correct.

Now if I put it into a class I get an error:
#!/usr/bin/python

class trying_it:
    def __init__(self):
	self.tmp = [[['a'],['one','two','three','four']],
		[['b'],['one','two','four','five']],
		[['c'],['one','two','three','six']],
		[['d'],['one','two','two','four']],
		[['e'],['one','ten','three','four']]] 
	
	self.kformat = ['one','two','three','four']

    def try_it(self):
	tmp2 = self.tmp[:]
	for i in (0,2,3):
	    tmp2 = filter(lambda x:x[1][i] in (self.kformat[i],),tmp2)
	return tmp2


a = trying_it()
a.try_it()

I get the error :
Traceback (innermost last):
  File "test_it.py", line 16, in ?
    a.try_it()
  File "test_it.py", line 11, in try_it
    tmp2 = filter(lambda x:x[1][i] in (self.kformat[i],),tmp2)
  File "test_it.py", line 11, in <lambda>
    tmp2 = filter(lambda x:x[1][i] in (self.kformat[i],),tmp2)
NameError: i 

I know this is a scoping problem, but what is the best way around it ?

regards
Matt




More information about the Python-list mailing list