在Python 3中,map()
返回一个迭代器对象,而不是一个列表。这些对象之间的相等测试将不起作用(相等是测试identity,内存中完全相同的对象)。
显式转换为列表:
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return list(map(s.find, s)) == list(map(t.index, t))
或使用列表理解:
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return [s.find(c) for c in s] == [t.index(w) for w in t]
或者通过将压缩结果与all()功能 https://docs.python.org/3/library/functions.html#all:
from operator import eq
from itertools import starmap, zip_longest
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return all(starmap(eq, zip_longest(map(s.find, s), map(t.index, t))))
如果不匹配,则后者会短路,而无需进行所有比较。本着保持功能风格的精神,我使用了itertools.starmap() https://docs.python.org/3/library/itertools.html#itertools.starmap测试是否与operator.eq()功能 https://docs.python.org/3/library/operator.html#operator.eq。通过使用itertools.zip_longest() https://docs.python.org/3/library/itertools.html#itertools.zip_longest我们确保能够检测到模式长度和字数不匹配的情况。