运行以下代码时出现此错误:
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!')
答案 0 :(得分:1)
您收到此错误,因为如果您使用length
输入1
,
for y in range(counter):
不会迭代任何内容,因此不会向results
添加任何内容。结果,您在索引位置0
或1
中没有任何内容。
也许您想将1
添加到for-loop范围。
<强>演示:强>
如果您在print('counter is ' + str(counter))
for循环中插入counter
,就可以看到这一点:
Mode: letters
Length: 1
Suffix: pup
Generating... (26 values)
counter is 0
追踪(最近一次通话): 文件&#34;&#34;,第39行,0 builtins.IndexError:列表索引超出范围
然后显然
>>>for x in range(0): print(x)
不会打印任何内容(这是您正在使用的行为)。