此:
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
的内容。什么?
答案 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/')]