我编写了这段代码,以网格形式显示列表的内容。 它适用于字母表列表。 但是,当我尝试使用随机生成的列表运行它时,它会给列表索引超出范围错误。我在处理我的python项目时遇到了错误:列表索引超出范围。
这里是全码: 进口随机
#barebones 2d shell grid generator
'''
Following list is a place holder
you can add any list data to show in a grid pattern with this tool
'''
lis = ['a','b','c','d','e','f','g','h','j','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newLis = []
#generates random list
def lisGen():
length = 20 # random.randint(10,20)
for i in range(length):
value = random.randint(1,9)
newLis.append(str(value))
lisGen()
askRow = input('Enter number of rows :')
askColumns = input('Enter number of columns :')
def gridGen(row,column):
j=0
cnt = int(row)
while (cnt>0):
for i in range(int(column)):
print(' '+'-',end='')
print('\n',end='')
#this is the output content loop
for i in range(int(column)):
if j<len(lis):
print('|'+newLis[j],end='')
j += 1
else:
print('|'+' ',end='')
print('|',end='')
print('\n',end='')
cnt -= 1
for i in range(int(column)):
print(' '+'-',end='')
print('\n',end='')
gridGen(askRow,askColumns)
预期的/正确的输出,使用字母表列表(LIS):
Enter number of rows :7
Enter number of columns :7
- - - - - - -
|a|b|c|d|e|f|g|
- - - - - - -
|h|j|i|j|k|l|m|
- - - - - - -
|n|o|p|q|r|s|t|
- - - - - - -
|u|v|w|x|y|z| |
- - - - - - -
| | | | | | | |
- - - - - - -
| | | | | | | |
- - - - - - -
| | | | | | | |
- - - - - - -
使用随机生成的列表时,该错误输出( newLis):
Enter number of rows :7
Enter number of columns :7
- - - - - - -
|9|2|1|4|7|5|4|
- - - - - - -
|9|7|7|3|2|1|3|
- - - - - - -
|7|5|4|1|2|3Traceback (most recent call last):
File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 56, in <module>
gridGen(askRow,askColumns)
File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 40, in gridGen
print('|'+newLis[j],end='')
IndexError: list index out of range
你所检查的'如果j
我错过了,谢谢你的帮助。 – USBEN