簡體   English   中英

在處理我的python項目時,我收到一個錯誤:列表索引超出范圍。

[英]I am getting an Error : list index out of range while working on my python project .

我編寫此代碼以網格形式顯示列表的內容。 它適用於字母表列表。 但是當我嘗試使用隨機生成的列表運行它時,它會給出列表索引超出范圍的錯誤。

這是完整的代碼:import random

#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

lisGen函數存在問題,它為列表生成固定數量的項目(例如,在您的情況下為20)。 它應該是row * cols。

這是更新代碼的鏈接

您的gridGen函數正在索引到newLis但它正在測試lis的大小而不是newLis 如果您將gridGen傳遞給要打印的列表而不是讓它訪問全局newLis那將是一個更好的設計。 這將使代碼更容易閱讀,並減少這樣的錯誤的幾率。 同樣, lisGen應該創建一個本地列表並返回它,而不是改變全局newLis

你的gridGen比它需要的更復雜。 我們可以通過創建我們想要打印的列表的迭代器並在該迭代器上調用next函數來簡化它。 我們給next一個默認的arg ' ' - 一個包含單個空格char的字符串,所以當列表用完時, next將返回空格。

我們不是逐個打印字符串,而是在列表推導中構建每一行,然后將行中的字符串連接成一個字符串。

這是我的程序版本。 我更改了名稱,使其符合PEP-8風格指南。

import random

random.seed(42)

def lis_gen():
    newlis = []
    length = 20
    for i in range(length):
        value = random.randint(1,9)
        newlis.append(str(value))
    return newlis

def grid_gen(lis, rows, cols):
    it = iter(lis)

    # Horizontal line
    hline = ' -' * cols
    print(hline)
    for j in range(rows):
        line = '|'.join([next(it, ' ') for i in range(cols)])
        print('|' + line + '|')
        print(hline)

ask_rows = 5
ask_cols = 7

alpha = list('abcdefghijklmnopqrstuvwxyz')
grid_gen(alpha, ask_rows, ask_cols)
print()

newlis = lis_gen()
grid_gen(newlis, ask_rows, ask_cols)

產量

 - - - - - - -
|a|b|c|d|e|f|g|
 - - - - - - -
|h|i|j|k|l|m|n|
 - - - - - - -
|o|p|q|r|s|t|u|
 - - - - - - -
|v|w|x|y|z| | |
 - - - - - - -
| | | | | | | |
 - - - - - - -

 - - - - - - -
|2|1|5|4|4|3|2|
 - - - - - - -
|9|2|7|1|1|2|4|
 - - - - - - -
|4|9|1|9|4|9| |
 - - - - - - -
| | | | | | | |
 - - - - - - -
| | | | | | | |
 - - - - - - -

請注意,我們實際上不需要在這里執行alpha = list('abcdefghijklmnopqrstuvwxyz') :如果我們將grid_gen傳遞給字符串而不是列表,它將迭代字符串中的每個字符。


grid_gen還有改進的grid_gen 通過更多的工作,我們可以巧妙地打印出包含多個char的字符串。 第一步是掃描輸入列表以查找它包含的最長字符串的長度。 如果lis是一個字符串列表,我們就可以這樣做

maxlen = max(map(len, lis))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM