python 3中的循环问题
我想要得到的东西是,识别某个特定列表项是否以与单词字符串相同的字母开头。每当我尝试试运行时,如果总是说:python 3中的循环问题,python,python-3.x,Python,Python 3.x,我想要得到的东西是,识别某个特定列表项是否以与单词字符串相同的字母开头。每当我尝试试运行时,如果总是说: def startsWith (word, lst): u=0 x=0 w=len(word) while u < len(lst): lest = lst[u] while x < len(word): if word[x].lower() == lest[x]:
def startsWith (word, lst):
u=0
x=0
w=len(word)
while u < len(lst):
lest = lst[u]
while x < len(word):
if word[x].lower() == lest[x]:
x=x+1
if word[x].upper() == lest[x]:
x=x+1
print (lst[u])
u=u+1
第二个if在最后一个x到达单词末尾后将有一个x值
>>> startsWith ('app',['apple','Apple','APPLE','pear','ApPle'])
Traceback (most recent call last):
File "<pyshell#92>", line 1, in <module>
startsWith ('app',['apple','Apple','APPLE','pear','ApPle'])
File "C:/Users/gpersaud/Desktop/hw3.py", line 35, in startsWith
if word[x].upper() == lest[x]:
IndexError: string index out of range
换成
if word[x].upper() == lest[x]:
或
更简洁的比较方法是word[x]。upper==lest[x]。upper虽然这两种方法都适用于整个字符串而不是单个字符,但您可能能够在更长的子字符串上调用它们。还有其他潜在问题。如果lest比word短,您仍然会得到一个索引器。并且x永远不会重置为0,因此第一个之后的大多数列表项将只检查一些中间字母,而列表中比前面最长的项目短的项目将根本不会被检查。如果需要按字符循环,我会使用for循环和zip。
if word[x].lower() == lest[x]:
x=x+1
elif word[x].upper() == lest[x]:
x=x+1
if word[x].lower() == lest[x] or word[x].upper() == lest[x]:
x=x+1