By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,526 Members | 1,618 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,526 IT Pros & Developers. It's quick & easy.

Re: Filter function and lists

P: n/a
John Townsend wrote:
Iím trying to figure out how to use filter to walk through a list.

If I try a simple scripts like this:

def greaterthanten (number):
#pdb.set_trace()
if (number 10):
ret_val = 1

else:
ret_val = 0

return ret_val

old_list = [1,2,20,30,5]

new_list = filter(greaterthanten, old_list)

#new_list becomes [20, 30]

The script works as I would expect. However, what if I need to pass more
than one argument to the function? Can I do that with filter? Or does
filter work only with function that take only a single arg?
The latter. Other functions could be wrapped to bind all parameters
except the list element. Or write an explicit loop.

Oct 29 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Oct 29, 4:28*pm, Terry Reedy <tjre...@udel.eduwrote:
John Townsend wrote:
Iím trying to figure out how to use filter to walk through a list.
If I try a simple scripts like this:
def greaterthanten (number):
* * * * * * * * #pdb.set_trace()
* * * * * * * * if (number 10):
* * * * * * * * * * * * * * * * ret_val= 1
* * * * * * * * else:
* * * * * * * * * * * * * * * * ret_val= 0
* * * * * * * * return ret_val
old_list = [1,2,20,30,5]
new_list = filter(greaterthanten, old_list)
#new_list becomes [20, 30]
The script works as I would expect. However, what if I need to pass more
than one argument to the function? Can I do that with filter? Or does
filter work only with function that take only a single arg?
That single argument could be a list.
>>old_list = [1,2,20,30,5]
>>def power_of_10(a):
if a[0]%10==0 and a[0]<a[1]:
return True
else:
return False
>>new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in old_list])]
new_list
[20, 30]
>>the_limit = 25
new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in old_list])]
new_list
[20]
>
The latter. *Other functions could be wrapped to bind all parameters
except the list element. *Or write an explicit loop.- Hide quoted text -

- Show quoted text -
Oct 30 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.