简体   繁体   English

为什么我的索引列表变量不能正常工作?

[英]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.我有一个randint变量,它可以 go 从 1 到字符串中的单词数量。 The string is currently 6 words long, thus the number can be between 1 and 6.该字符串目前有 6 个字长,因此数字可以在 1 到 6 之间。

If the number is greater than 4, I want it to be 4. I tried using the following snippet of code:如果数字大于 4,我希望它是 4。我尝试使用以下代码片段:

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. Python 中的列表是零索引的。 The index of the first element in a list is 0.列表中第一个元素的索引为 0。

In a list of 4 elements, the last element index is 3, not 4.在 4 个元素的列表中,最后一个元素索引是 3,而不是 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.您使用wwlIndexer做对了,但问题在于访问数组。

In most programming languages arrays begin counting from 0, not from 1.在大多数编程语言中,arrays 从 0 开始计数,而不是从 1 开始计数。

The last element of WhatWordList = ['st', 'nd', 'rd', 'th'] is WhatWordList[3] , not WhatWordList[4] WhatWordList = ['st', 'nd', 'rd', 'th']的最后一个元素是WhatWordList[3] ,而不是WhatWordList[4]

So first, in Python, according to PEP-8 guidelines, you want to declare variables like one_variable , not like oneVariable .因此,首先,在 Python 中,根据 PEP-8 准则,您要声明变量,如one_variable而不是oneVariable And then, in WhatWordList are four elements.然后,在WhatWordList中有四个元素。 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 .但是由于 Python 将列表的第一个元素索引为 0,第二个元素索引为 1,依此类推,列表的最后一个元素的索引为 3。因此,如果wwlIndexer >= 4 ,您的代码将不起作用。 You may try the using the following line of code:您可以尝试使用以下代码行:

ordinal = what_word_list[wwl_indexer-1]

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

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