Q(编写一个函数时,如果两个单词都以同一个字母开头,则使用两个单词的字符串并返回True。
以下是我尝试过的
def animal_crackers(text):
for x,y in text.split():
if x[0].lower() == y[0].lower():
return True
else:
return False
这里显示了错误-
太多的值无法解包(预期为2(
对于线路2-for x,y in text.split():
我不明白为什么会出现这个错误,因为它只有两个字要打开。
for x, y in
意味着您将在多对上循环。如果只有一对,则需要x, y =
。
def animal_crackers(text):
x, y = text.split()
return x[0].lower() == y[0].lower()
>>> animal_crackers('foo bar')
False
>>> animal_crackers('bar baz')
True
顺便说一下,我简化了另一部分。
说明
你之所以会出现这个错误,是因为你提供的第一个单词有两个以上的字母。例如:
def f(text):
for x, y in text.split():
return x[0].lower() == y[0].lower()
>>> f('hh')
True
>>> f('hb')
False
>>> f('i')
...
ValueError: not enough values to unpack (expected 2, got 1)
>>> f('iii')
...
ValueError: too many values to unpack (expected 2)
您正在拆包这两个字符串,这也是在for
循环中。这就是导致代码中出现错误的原因。
假设我们输入"Lion Leapord"
,那么在第一次迭代中,您的函数将x
和y
中的"L"one_answers"i"进行比较,这可能不是您想要做的
所以只需更换
for x,y in text.split():
带有
x,y = text.split()
所以最后你的功能会是这样的:
def animal_crackers(text):
x,y = text.split()
print(x,y)
if x[0].lower() == y[0].lower():
return True
else:
return False
通过编写进行测试
animal_crackers("Lion Leapord")
给出True
animal_crackers("Lion Elephant")
给出False