Python处理列表的奇怪之处

时间:2014-10-25 06:56:00

标签: python python-3.x

此:

import sys, re

# List of file names to exclude from analysis
excludes = map(re.compile, [
    '/\.svn/',
    '/\.hg/', ])


def regmatch(pathName):
    # Print the argument then any regular expressions that match it
    sys.stdout.write("::" + pathName + "\n")
    for pattern in excludes:
        sys.stdout.write("\t" + str(re.search(pattern, pathName)) + "\n")

regmatch("one/.hg/one")
regmatch("two/.hg/two")
regmatch("thr/.hg/thr")
Python2.7中的

产生预期的结果,即,对于每个调用,它打印参数,然后是匹配每个re的结果列表。但是,在Python3中,输出是:

::one/.hg/one
        None
        <_sre.SRE_Match object at 0xb74bb870>
::two/.hg/two
::thr/.hg/thr

即,在第一次通话后似乎忘记了excludes的内容。什么?

1 个答案:

答案 0 :(得分:2)

因为在Python 3.x中,map 不返回列表,而是返回迭代器

  

返回一个迭代器,它将函数应用于iterable的每个项目,从而产生结果。

因此,一旦迭代器耗尽,就无法再次使用它。在您第一次调用regmatch时,excludes迭代器已用完。因此,在随后的for调用中,regmatch循环的进一步迭代将立即退出。

要解决此问题,您可以显式创建列表,例如

excludes = list(map(re.compile, ['/\.svn/', '/\.hg/']))

或者你可以使用列表理解,就像这样

excludes = [re.compile(item) for item in ('/\.svn/', '/\.hg/')]