Arindam Roychowdhury
Arindam Roychowdhury

Reputation: 6521

Python : Pass two values to function used in filter

I made a filter function to filter out file types in a list of file names .

>>> l1
['180px-Cricketball.png', 'AgentVinod_450.jpg', 'Cricketball.bmp', 'Django-1.4', 'Django-1.4.tar.gz', 'Firefox Setup 11.0.exe', 'I-Will-Do-The-Talking-Tonight-(Muskurahat.Com).mp3', 'kahaani-.jpg', 'Never gonna leave this bed.mp3', 'Piya-Tu-Kaahe-Rootha-Re-(Muskurahat.Com).mp3', 'pygame-1.9.1release', 'pygame-1.9.1release.zip', 'pygame-1.9.2a0.win32-py2.7.msi', 'python-2.7.2.msi', 'python-3.1.2.msi', 'Resume.doc', 'selenium-2.20.0', 'selenium-2.20.0.tar.gz', 'sqlite-shell-win32-x86-3071100.zip', 'wxdesign_220a.exe', 'YTDSetup.exe']
>>> def myfilt(subject):
    if re.search('.jpg',subject):
        return True


>>> filter(myfilt,l1)
['AgentVinod_450.jpg', 'kahaani-.jpg']

This works fine.

Now suppose I want make this more flexible. I want to pass file type to the function . So I rewrite the function

>>> def myfilt(subject,filetype):
    if re.search(filetype,subject):
        return True

Now how do I pass the filetype through the filter function?

I tried:

>>> filter(myfilt(l1,filetype),l1)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    filter(myfilt(l1,filetype),l1)
  File "<pyshell#28>", line 2, in myfilt
    if re.search(filetype,subject):
  File "C:\Python27\lib\re.py", line 142, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

Nothings works. Any ideas?

Upvotes: 0

Views: 3438

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602715

You would usually use a list comprehension rather than filter() for such cases:

[x for x in l1 if myfilt(x, filetype)]

If you really want to use filter(), you could use a lambda function

filter(lambda x: myfilt(x, filetype), l1)

or functools.partial():

filter(functools.partial(myfilt, filetype=filetype), l1)

The list comprehension seems the easiest and most readable option, though.

Upvotes: 10

Related Questions