我是编码的初学者.我正在寻找这个问题的解决方案:我应该编写一个函数,它可以很好地接受带有单词和数字的文本字符串,用空格分隔,如果连续有3个单词则输出True.
例:
'123 a b c' == True
'a 123 b c' == False
Run Code Online (Sandbox Code Playgroud)
我尝试过的:
def 3_in_a_row(words):
words = words.split(" ")
for i in range(len(words)):
return words[i].isalpha() and words[i+1].isalpha() and words[i+2].isalpha()
Run Code Online (Sandbox Code Playgroud)
如果我尝试这个,我会收到一个list index out of range错误,因为当我接近列表的末尾时,i检查后没有2个单词.
限制此功能的最佳方法是什么,以便在i检查后没有2个项目时停止?有什么更好的方法呢?
您可以限制范围:
range(len(words) - 2)
Run Code Online (Sandbox Code Playgroud)
所以它不会产生你不能添加2的索引.
但是,你的循环太早了.您只返回测试前3个单词的结果.'123 a b c'例如,您的测试将失败,因为仅'123', 'a', 'b'在第一次迭代中进行测试.改变你的循环:
def three_in_a_row(words):
words = words.split(" ")
for i in range(len(words) - 2):
if words[i].isalpha() and words[i+1].isalpha() and words[i+2].isalpha():
return True
return False
Run Code Online (Sandbox Code Playgroud)
如果你连续发现三个单词,现在会提前返回,只有在扫描完所有单词后才会声明失败并返回False.
其他一些提示:
您无法使用数字启动Python标识符(如函数名称).第一个字符必须是一个字母.我将上面的函数重命名为three_in_a_row().
words.split()不带参数使用.它在任意空格上分裂,并在开头和结尾忽略空格.这意味着即使在某处之间偶尔有2个空格,或者在结尾处有换行符或制表符,拆分也会起作用.
您可以使用该all()函数在循环中测试事物:
if all(w.isalpha() for w in words[i:i + 3]):
Run Code Online (Sandbox Code Playgroud)
是一种更紧凑的拼写相同测试方式.
演示这些更新:
>>> def three_in_a_row(words):
... words = words.split()
... for i in range(len(words) - 2):
... if all(w.isalpha() for w in words[i:i + 3]):
... return True
... return False
...
>>> three_in_a_row('123 a b c')
True
>>> three_in_a_row('a 123 b c')
False
>>> three_in_a_row('a b c 123')
True
Run Code Online (Sandbox Code Playgroud)