Value Generator - IndexError: list index out of range - Python

Value Generator - IndexError: list index out of range - Python

当 运行 下面的代码时出现此错误:

Traceback (most recent call last):
  File "C:/Users/Reum/Desktop/Generator.py", line 35, in <module>
    print(results[0], results[1])
IndexError: list index out of range

我使用 while 循环用逗号分隔值,而不是这样:

"'value1', 'value2', ..."

我在 while 循环中使用 if 循环来捕获最新的输出并对其进行修改,使其末尾没有逗号。

我希望你能解决我的(可能是愚蠢的)问题。

import sys, time

mode = input('Mode:' + ' ')

if mode == 'letters' or mode == 'Letters':
    chars = 'abcdefghijklmnopqrstuvwxyz'
    letters = True
elif mode == 'numbers' or mode == 'Numbers':
    chars = '0123456789'
    numbers = True
elif mode == 'custom' or mode == 'Custom':
    chars = 'abcde' #Enter some custom chars between the quotation marks.
    custom = True

length = input('Length:' + ' ')
suffix = input('Suffix:' + ' ')

if letters:
    variations = 26 ** int(length)
elif numbers:
    variations = 10 ** int(length)
elif custom:
    variations = 5 ** int(length) #Count the numbers of chars from above and replace the 5 with the outcome of your brain.

print('Generating...' + ' ' + '(' + str(variations) + ' ' + 'values)')

results = []

for counter in range(int(length)):
    char = [x for x in chars]
    for y in range(counter):
        char = [z + x for x in chars for z in char]
        results = results + char

print(results[0], results[1])
print('Results: \n')

counter = 0

while another_counter < variations:
    sys.stdout.write(results[another_counter] + suffix + ',' + ' ')
    time.sleep(0.005)
    counter = counter + 1
    if counter == variations -1: #Maybe not.
        sys.stdout.write(results[counter] + suffix)

print('Finished generating and displaying the values!')

出现此错误是因为如果您使用 1

length 输入
for y in range(counter):

不会迭代任何内容,因此不会向您的 results 添加任何内容。结果,您在索引位置 01 中将没有任何内容。

也许您想将 1 添加到您的 for 循环范围。


演示:

如果您在 counter for 循环中插入 print('counter is ' + str(counter)),您会看到这个:

Mode: letters
Length: 1
Suffix: pup
Generating... (26 values)
counter is 0

Traceback (most recent call last): File "", line 39, in 0 builtins.IndexError: list index out of range

那么显然

>>>for x in range(0): print(x)

不打印任何内容(这是您的行为)。