简体   繁体   中英

Why won't my indexed list variable work properly?

I have a randint variable that can go from 1 to the amount of words in a string. The string is currently 6 words long, thus the number can be between 1 and 6.

If the number is greater than 4, I want it to be 4. I tried using the following snippet of code:

if wwlIndexer > 4:
    wwlIndexer = 4

ordinal = WhatWordList[wwlIndexer]

But that gives back the following error message:

 list index out of range -
   File "C:\Users\redacted\Coding bullshit\Experimentation.py", line 16, in <module>
     ordinal = WhatWordList[wwlIndexer]

For context, the whole code I'm trying to make work looks like this:

from random import randint

print('--------------------')

myString = 'I am a cool little bastard'
WhatWordList = ['st', 'nd', 'rd', 'th']
wwlIndexer = 0

for n in range(5):
    myStringLength = len(myString.split(' '))
    randomNumber = randint(1, myStringLength)
    wwlIndexer = randomNumber 
    if wwlIndexer > 4:
        wwlIndexer = 4

    ordinal = WhatWordList[wwlIndexer]

    print('----')
    print('The length of the string is:', myStringLength, 'words')
    print('The random number is', randomNumber)

    print('The ' + str(randomNumber) + str(ordinal) + ' is ' + str(myString.split(' ')[randomNumber - 
1]))
    print('----')
    print()
    print()

Lists in Python are zero-indexed. The index of the first element in a list is 0.

In a list of 4 elements, the last element index is 3, not 4.

You are seeking for an answer to the wrong problem. You did it right with wwlIndexer but the problem is with accessing the array.

In most programming languages arrays begin counting from 0, not from 1.

The last element of WhatWordList = ['st', 'nd', 'rd', 'th'] is WhatWordList[3] , not WhatWordList[4]

So first, in Python, according to PEP-8 guidelines, you want to declare variables like one_variable , not like oneVariable . And then, in WhatWordList are four elements. But as Python indexes the first element of a list as 0, the second one as 1 etc., the list's last element has an index of 3. Thus your code won't work if wwlIndexer >= 4 . You may try the using the following line of code:

ordinal = what_word_list[wwl_indexer-1]

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