简体   繁体   中英

python: IndexError: string index out of range

m learning python from the google tutorials. 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.

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.

If you wanted to add elements to that list, use lis.append() instead.

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:

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:

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') ; False is sorted before True so we negate that test, then the words themselves.

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.

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:

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.
  2. You want to remove the word starting with "x" at index i from the list, but pop() will always remove the last item. pop() is for stacks; 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; thus the IndexError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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