Python:将两个值传递给fi中使用的函数

2024-09-30 12:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个过滤器函数来过滤文件名列表中的文件类型。在

>>> 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']

这个很好用。在

现在假设我想让它更灵活。我想把文件类型传递给函数。 所以我重写了函数

^{pr2}$

现在如何通过filter函数传递文件类型?在

我试过了:

>>> 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

什么都不管用。有什么想法吗?在


Tags: 函数rel1searchfilterexepygamemp3
1条回答
网友
1楼 · 发布于 2024-09-30 12:21:40

对于这种情况,通常使用列表理解而不是filter()

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

如果您真的想使用filter(),可以使用lambda函数

^{pr2}$

functools.partial()

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

不过,列表理解似乎是最简单、最易读的选择。在

相关问题 更多 >

    热门问题