简体   繁体   English

Python:尝试在索引处比较两个字符串时,列表索引超出范围?

[英]Python: list index out of range when trying to compare two strings at index?

I have this function to check if a string contains three or more lowercase letters. 我具有此功能来检查字符串是否包含三个或更多个小写字母。

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

In simple terms, I pass in a string (word) and create a list of acceptable characters (lowCharList). 简单来说,我传入一个字符串(单词)并创建一个可接受的字符列表(lowCharList)。

Then, I set up a nested while loop that checks word[i] at every index of lowCharList, until it finds a match. 然后,我建立了一个嵌套的while循环,该循环在lowCharList的每个索引处检查word [i],直到找到匹配项为止。

Then it resets lowCharList counter and adds 1 to flag, and moves on to word[i+1]. 然后,它重置lowCharList计数器并将1加到标志,然后移至word [i + 1]。

If it doesn't find a match by the time it reaches z, then it moves onto word[i+1] anyways. 如果在到达z时找不到匹配项,则它将继续移动到单词[i + 1]上。

For some reason, why I try my sample input in my main function. 由于某些原因,为什么要在主函数中尝试输入示例。

def main():
  word = 'corRe!33'
  print(lowerCaseValid(word))

I get this error: 我收到此错误:

in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range

Why is it throwing this error? 为什么会引发此错误? Thank you. 谢谢。

using python's in operator is easier... 使用python的in运算符更容易...

    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 或仅使用2行代码

def lowerCaseValid(word):

    lowCharList = ['abcdefghijklmnopqrstuvwxyz']

    return len(set(lowCharList.pop()) & set(word)) >=3

or one liner with map and lambda 或一张带有地图和lambda的班轮

def lowerCaseValid(word):

    return len(list(map(lambda x: x.islower, list(word)))) >=3

Another alternative approach using a list comprehension and string.ascii_lowercase instead of redefining the lowercase letters: 使用列表推导和string.ascii_lowercase而不是重新定义小写字母的另一种替代方法:

from string import ascii_lowercase

def lowerCaseValid(word):
    return sum[x in ascii_lowercase for x in word] >= 3

How this works is that the list comprehension goes through each letter in word. 列表的理解是如何遍历单词中的每个字母的。 The x in ascii_lowercase will return a boolean value of either True (1) or False (0), then sum up the True s x in ascii_lowercasex in ascii_lowercase将返回布尔值True(1)或False(0),然后对True sum

Change 更改

lowCharList = ['abcdefghijklmnopqrstuvwxyz']

to

lowCharList = list('abcdefghijklmnopqrstuvwxyz')

I believe this should help, since you have a list containing only 1 item, whereas this way, you create a list with 24 items (all different letters). 我相信这会有所帮助,因为您的列表仅包含1个项目,而这样,您将创建一个包含24个项目(所有字母均不同)的列表。

As heemayl pointed out in the comments, lowCharList is 1 element long! 正如heemayl在评论中指出的那样, lowCharList为1个元素! Now you have 2 options: make lowCharList an actual list ( lowCharList = list ("abcd...") ), or keep lowCharList a string, which will work just fine (remove the brackets in the definition. 现在,您有2个选项:将lowCharList设置为实际列表( lowCharList = list ("abcd...") ),或将lowCharList保留为字符串,这将正常工作(删除定义中的括号)。

Might I suggest another method: checking if str.islower count adds up to >=3. 可能我建议另一种方法:检查str.islower计数是否总计> = 3。 So: 所以:

lower_count = 0
for letter in word: 
    if letter.islower(): lower_count += 1
if lower_count >= 3: return True

Also, as suggested in the comments: 另外,如评论中所建议:

return len ([letter for letter in word if letter.islower()]) >= 3 

would work (better than my answer, which is just the expanded form of it) 会起作用(比我的答案更好,这只是它的扩展形式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM