Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用带有find和index的map时Python2和Python3之间的差异_Python_Python 3.x_Map Function - Fatal编程技术网

使用带有find和index的map时Python2和Python3之间的差异

使用带有find和index的map时Python2和Python3之间的差异,python,python-3.x,map-function,Python,Python 3.x,Map Function,给定一个模式和一个字符串str,查找str是否遵循相同的模式 这里的follow表示完全匹配,例如模式中的字母和str中的非空单词之间存在双射 示例: pattern=“abba”,str=“dog-cat-dog”应返回truedog是a,cat是b,单词构成abba模式。 pattern=“abba”,str=“dog-cat-fish”应返回false;字符串遵循abbc模式 我的解决方案适用于Python 2: def wordPattern(self, pattern, str):

给定一个模式和一个字符串
str
,查找
str
是否遵循相同的模式

这里的follow表示完全匹配,例如模式中的字母和
str
中的非空单词之间存在双射

示例:
pattern=“abba”
str=“dog-cat-dog”
应返回true
dog
a
cat
b
,单词构成
abba
模式。
pattern=“abba”
str=“dog-cat-fish”
应返回false;字符串遵循
abbc
模式

我的解决方案适用于Python 2:

def wordPattern(self, pattern, str):
    s = pattern
    t = str.split()
    return map(s.find, s) == map(t.index, t)
但我只是想知道为什么这个解决方案在Python3中不起作用。在这里,当尝试测试上述示例时,函数将始终返回
False
。谁能给点建议吗

在Python 3中,
map()
返回迭代器对象,而不是列表。这些对象之间的相等性测试不起作用(相等性是测试标识,而不是内存中完全相同的对象)

显式转换为列表:

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]
或者,通过将压缩结果与以下内容进行比较,避免完全创建列表:


后者短路,如果不匹配,则无需进行所有比较。本着保持功能性风格的精神,我曾经测试过与。通过使用,我们确保可以检测到模式长度和字数不匹配的情况。

map返回python 3Use list中的生成器(map(…))感谢您的更正:)您的已经讲述了要讲述的故事,所以我的非常精彩。我听说
list1==list2
比较也短路,对吗?请参见此处的注释@Chris_Rands:确实如此,但您首先必须进行两次完整的迭代才能创建列表。@MartijnPieters我认为最后一种解决方案只有在
s
t
具有相同数量的元素时才有效。我遗漏了什么吗?wordPattern(None,“abba”,“dog-cat-dog”)应该返回false,最后一个示例返回true。我想你应该先检查元素的数量
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))))