引用列表中的下一个项目
我正在编写一个程序,要求我确定字符串列表是否是单词链。 词链是一个单词列表,其中单词的最后一个字母是最后一个单词的下一个字母的第一个字母。如果列表是单词链,程序将返回 True,否则返回 false。我的代码如下:
def is_word_chain(word_list):
for i in word_list:
if i[-1] == (i+1[0]):
result = True
else:
result = False
return result
它返回以下错误:
SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
if i[-1] == (i+1[0]):
Traceback (most recent call last):
if i[-1] == (i+1[0]):
TypeError: 'int' object is not subscriptable
我想知道如何正确引用列表中的下一项才能执行此函数。
I am working through a program that requires me to determine if a list of strings is a word chain. A word chain is a list of words in which the last letter of a word is the first letter of the next word in the last. The program is to return True if the list is a word chain, and false otherwise. My code is as follows:
def is_word_chain(word_list):
for i in word_list:
if i[-1] == (i+1[0]):
result = True
else:
result = False
return result
and it returns the following error:
SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
if i[-1] == (i+1[0]):
Traceback (most recent call last):
if i[-1] == (i+1[0]):
TypeError: 'int' object is not subscriptable
I am wondering how I would properly reference the next item in the list in order to execute this function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
给定:
您可以使用
zip
获取一对单词进行测试:一旦获得,您可以返回
True
或False
,如下所示:Given:
You can use
zip
to get a pair of words to test:Once you have that, you can return
True
orFalse
like so:修好了:)
Fixed it :)
在您的代码中,您迭代字符串,并且在 if 条件下,您尝试使用该字符串作为列表,这在技术上是错误的。
使用 range 并将 word_chain 作为列表进行迭代。
in your code you iterate through strings and in if condition you are trying use that string as sort of list which is technically blunder here.
use range and iterate over word_chain as list.