Python 在列表中查找单词的数量
这是我的问题: 如果字符串“cat”和“dog”出现的次数相同,则返回True 在给定的字符串中。 我曾尝试使用计数方法,但它不起作用 这是我的密码:Python 在列表中查找单词的数量,python,Python,这是我的问题: 如果字符串“cat”和“dog”出现的次数相同,则返回True 在给定的字符串中。 我曾尝试使用计数方法,但它不起作用 这是我的密码: def catdog(list): a = list.count("cat") b = list.count("dog") if a == b: return True print(catdog(["cat,dog"])) print(ca
def catdog(list):
a = list.count("cat")
b = list.count("dog")
if a == b:
return True
print(catdog(["cat,dog"]))
print(catdog(["cat,cat"]))
它输出true和true,并且应该是true和false。这是输出,因为您传递的列表只有一个字符串:
“猫,狗”
我猜您希望这是两个不同的字符串:[“猫”、“狗”]
另外,您可以直接
返回a==b
。它更具可读性。您的问题是,您正在传入一个包含一个字符串的列表,其中包含以下行:
print(catdog(["cat,dog"]))
括号[
使其成为一个列表,引号“
在列表中形成一个字符串,因此它是一个一项的列表。
您应该选择传递列表或字符串,但不能在另一个列表或字符串中传递一个
因此,要么:
print(catdog("cat,dog"))
或:
这两种方法都可以工作,因为Python在str
和list
上都有count
方法,这两种方法做的事情相同。这样更好:
def catdog(x):
a = x.count('dog')
b = x.count('cat')
if a == b:
return True
pets = ['cat','dog']
print(catdog(pets))
如果让函数返回某些内容,则必须使用“打印”函数。或者,也可以在函数中使用“打印”:
def catdog(x):
a = x.count('dog')
b = x.count('cat')
if a == b:
print('Cats and dogs are equal.')
pets = ['cat','dog']
catdog(pets)
def catdog(x):
a = x.count('dog')
b = x.count('cat')
if a == b:
print('Cats and dogs are equal.')
pets = ['cat','dog']
catdog(pets)