def animal_crackers(text):
for [word1, word2] in text.split():
if word1[0]==word2[0]:
return true
else:
pass
animal_crackers('Levelheaded Llama')ValueError Traceback (most recent call last)
<ipython-input-21-bfc977603445> in <module>()
5 else:
6 pass
----> 7 animal_crackers('Levelheaded Llama')
<ipython-input-21-bfc977603445> in animal_crackers(text)
1 def animal_crackers(text):
----> 2 for [word1, word2] in text.split():
3 if word1[0]==word2[0]:
4 return true
5 else:
ValueError: too many values to unpack (expected 2)发布于 2018-12-25 13:07:06
text.split()返回['Levelheaded', 'Llama'],因此我们得到:
for [word1, word2] in ['Levelheaded', 'Llama']:
if word1[0]==word2[0]:
return true
else:
pass现在,由于我们知道在两个元素的列表上有一个循环,所以我们可以这样展开循环:
# First iteration
[word1, word2] = 'Levelheaded'
if word1[0]==word2[0]:
return true
else:
pass
# Second iteration
[word1, word2] = 'Llama'
if word1[0]==word2[0]:
return true
else:
pass现在,像[word1, word2] = 'Levelheaded'这样的东西将把字符串看作是一个字符列表,但是由于单词包含两个以上的字符,所以会出现错误。
由于您实际上不想遍历任何内容,所以应该去掉for循环,只需编写:
[word1, word2] = text.split()发布于 2018-12-25 13:01:33
split返回一个字符串列表,如果该字符串不包含用作分隔符的字符串,则边大小写为带有单个字符串的列表。
通过说for [word1, word2] in text.split(),您实际上希望它返回一个列表列表,如下所示:
for [word1, word2] in [['a', 'b'], ['c', 'd']]:
print(word1, word2)威尔输出
a b
c d你有两个选择:
text总是有一个空格,或者如果您希望得到错误,否则):
word1,word2 = text.split()发布于 2018-12-25 13:04:51
代码中的问题是,您试图将一个值赋值给两个变量,这里的text.split()是['Levelheaded', 'Llama'],所以您要迭代的元素的第一个元素将是'Levelheaded',您试图分配给两个变量word1和word2。
相反,您可以在不迭代的情况下分配它们,还可以将true更改为True。
def animal_crackers(text):
word1, word2 = text.split()
if word1[0] == word2[0]:
return True
print(animal_crackers('Levelheaded Llama')) # -> Truehttps://stackoverflow.com/questions/53922582
复制相似问题