简体   繁体   English

python:IndexError:字符串索引超出范围

[英]python: IndexError: string index out of range

m learning python from the google tutorials. 我从Google教程中学习python。 am stuck on an exercise related to lists. 被困在与清单有关的练习中。 getting an index error 出现索引错误

  lis[j]=words.pop()[i]
IndexError: string index out of range

i need to sort the list but the words starting with x should be the first ones. 我需要对列表进行排序,但是以x开头的单词应该是第一个。

code is 代码是

def front_x(words):
    i=0
    lis=[]
    j=0
    k=0
    words.sort()

    while i<len(words):
        if words[i][0:1]=="x":
            lis[j]=words.pop()[i]
            j+=1
        i+=1
    lis.extend(words)
    while k<len(lis):
        print(lis[k])
        k+=1
    return

lis is an empty list, any index will raise an exception. lis是一个空列表, 任何索引都会引发异常。

If you wanted to add elements to that list, use lis.append() instead. 如果要将元素添加到该列表,请改用lis.append()

Note that you can loop over sequences directly , there is no need to keep your own counter: 请注意,您可以直接循环序列,而无需保留自己的计数器:

def front_x(words):
    lis = []
    words.sort()

    for word in words:
        if word.startswith("x"):
            lis.append(word)
    for entry in lis:
        print(entry)

You can reduce this further by immediately printing all words that start with x , no need to build a separate list: 您可以通过立即打印以x开头的所有单词来进一步减少这种情况,而无需构建单独的列表:

def front_x(words):
    for word in sorted(words):
        if word.startswith("x"):
            print(word)

If you wanted to sort the list with all x words coming first, use a custom sort key: 如果要对列表进行排序,且所有x单词都在前,请使用自定义排序键:

def front_x(words):
    return sorted(words, key=lambda w: (not w.startswith('x'), w))

sorts the words first by the boolean flag for .startswith('x') ; 首先按.startswith('x')的布尔标志对.startswith('x')进行.startswith('x') False is sorted before True so we negate that test, then the words themselves. FalseTrue之前排序,因此我们先否定该测试,然后否定单词本身。

Demo: 演示:

>>> words = ['foo', 'bar', 'xbaz', 'eggs', 'xspam', 'xham']
>>> sorted(words, key=lambda w: (not w.startswith('x'), w))
['xbaz', 'xham', 'xspam', 'bar', 'eggs', 'foo']

i need to sort the list but the words starting with x should be the first ones. 我需要对列表进行排序,但是以x开头的单词应该是第一个。

Complementary to the custom search key in @Martijn's extended answer, you could also try this, which is closer to your original approach and might be easier to understand: 与@Martijn扩展答案中的自定义搜索键互补,您也可以尝试使用此方法,它更接近于您的原始方法,并且可能更易于理解:

def front_x(words):
    has_x, hasnt = [], []
    for word in sorted(words):
        if word.startswith('x'):
            has_x.append(word)
        else:
            hasnt.append(word)
    return has_x + hasnt

Concerning what was wrong with your original code, there are actually three problems with the line 关于原始代码出了什么问题,该行实际上存在三个问题

lis[j]=words.pop()[i]
  1. lis[j] only works if the list already has a j th element, but as you are adding items to an initially empty list, you should use lis.append(...) instead. lis[j]仅在列表中已有第j个元素时才有效,但是当您将项目添加到最初为空的列表中时,应改用lis.append(...)
  2. You want to remove the word starting with "x" at index i from the list, but pop() will always remove the last item. 您想从列表中的索引i处删除以“ x”开头的单词,但是pop()始终会删除最后一个项目。 pop() is for stacks; pop()用于堆栈; never remove items from a list while looping it with an index! 切勿在使用索引循环时从列表中删除项目!
  3. You apply the [i] operator after you've popped the item from the list, ie, you are accessing the i th letter of the word , which may be much shorter; 从列表中弹出项目后,即可应用[i]运算符,即,您正在访问单词的i字母,该字母可能短得多; thus the IndexError 因此, IndexError

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

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