函数中的Python在元组中找不到字符串?
在上面的代码中,第6行应该找到公共元素在4对活动之间移动的次数。这个例子应该返回4,因为fishing是一个常见的元素,发生了4次。但是,它返回0。我认为这是因为common不仅仅是一个字符串,而是一个字符串列表,但我不知道如何将res转换为一个字符串。有什么建议吗?一个简单的函数中的Python在元组中找不到字符串?,python,intersection,Python,Intersection,在上面的代码中,第6行应该找到公共元素在4对活动之间移动的次数。这个例子应该返回4,因为fishing是一个常见的元素,发生了4次。但是,它返回0。我认为这是因为common不仅仅是一个字符串,而是一个字符串列表,但我不知道如何将res转换为一个字符串。有什么建议吗?一个简单的print语句可以清楚地说明问题: def bestInvitation(first, second): yeah=tuple(zip(first, second)) res=list(set.inters
print
语句可以清楚地说明问题:
def bestInvitation(first, second):
yeah=tuple(zip(first, second))
res=list(set.intersection(*map(set, yeah)))
common=str(res)
count=0
for i in yeah:
if common in i:
count+=1
return count
if __name__ == '__main__':
print(bestInvitation(["fishing", "gardening", "swimming", "fishing"],
["hunting", "fishing", "fishing", "biting"]))
输出:
...
for i in yeah:
print(common, i)
if common in i:
...
您没有在字符串元组中搜索字符串:您搜索的是元组中包含字符串的列表的字符串图像。由于元组中没有这样的实体,if
语句在每次迭代中都会失败
修复数据处理--一行:
['fishing'] ('fishing', 'hunting')
['fishing'] ('gardening', 'fishing')
['fishing'] ('swimming', 'fishing')
['fishing'] ('fishing', 'biting')
现在,您获得了所需的
4
输出,一个简单的打印
语句可以清楚地说明问题:
def bestInvitation(first, second):
yeah=tuple(zip(first, second))
res=list(set.intersection(*map(set, yeah)))
common=str(res)
count=0
for i in yeah:
if common in i:
count+=1
return count
if __name__ == '__main__':
print(bestInvitation(["fishing", "gardening", "swimming", "fishing"],
["hunting", "fishing", "fishing", "biting"]))
输出:
...
for i in yeah:
print(common, i)
if common in i:
...
您没有在字符串元组中搜索字符串:您搜索的是元组中包含字符串的列表的字符串图像。由于元组中没有这样的实体,if
语句在每次迭代中都会失败
修复数据处理--一行:
['fishing'] ('fishing', 'hunting')
['fishing'] ('gardening', 'fishing')
['fishing'] ('swimming', 'fishing')
['fishing'] ('fishing', 'biting')
现在您可以获得所需的4
输出