我有这个函数来检查字符串是否包含三个或更多小写字母。
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
i = 0
flag = 0
while i <= len(word):
j = 0
while j <= len(lowCharList):
if lowCharList[j] == word[i]:
flag += 1
j = 0
else:
j += 1
i += 1
if flag >= 3:
return True
简单来说,我传入一个字符串(单词)并创建可接受的字符列表(lowCharList)。
然后,我设置了一个嵌套的 while 循环来检查 lowCharList 的每个索引处的 word[i],直到找到匹配项。
然后它重置 lowCharList 计数器并将标志加 1,然后移至 word[i+1]。
如果到达 z 时未找到匹配项,则无论如何都会移至 word[i+1]。
出于某种原因,为什么我在主函数中尝试示例输入。
def main():
word = 'corRe!33'
print(lowerCaseValid(word))
我收到此错误:
in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range
为什么会抛出这个错误?谢谢。
最佳答案
using python's in operator is easier...
def lowerCaseValid(word):
cnt = 0
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
chars = lowCharList.pop ()
for ch in word:
if ch in chars:
cnt += 1
return cnt >= 3
or with using sets just 2 lines of code
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
return len(set(lowCharList.pop()) & set(word)) >=3
or one liner with map and lambda
def lowerCaseValid(word):
return len(list(map(lambda x: x.islower, list(word)))) >=3
关于Python:尝试比较索引处的两个字符串时列出索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978412/