2017-05-31 32 views
1

我想根據用戶需要獲取嵌套列表的尺寸。 然後將用戶給出的字符串附加到相應的元素。 在嵌套列表中查找最大長度的字符串以正確地左對齊文本。 然後左對齊字符串以表格形式打印字符串。 程序應該去了解這個附加到一個未知尺寸的嵌套列表

Enter the number of main items in the list: 3 
Enter the number of sub items that each list will contain: 4 
(1,1):apples 
(1,2):oranges 
(1,3):cherries 
(1,4):banana 
(2,1):Alice 
(2,2):Bob 
(2,3):Carol 
(2,4):David 
(3,1):dogs 
(3,2):cats 
(3,3):moose 
(3,4):goose 
Following list must be created in the program 
listOfList= [ ['apples', 'oranges', 'cherries', 'banana'], 
       ['Alice', 'Bob', 'Carol', 'David'], 
       ['dogs', 'cats', 'moose', 'goose']] 
output given by a print table function should be like this: 
''' 
apples Alice dogs 
oranges Bob cats 
cherries Carol moose 
banana David goose 

這裏是我的實際代碼

#Organising Lists of Lists in tablular Form 
x=int(input("Enter the number of main items in the list: ")) 
y=int(input("Enter the number of sub items that each list will contain: ")) 
listOfList=[[]] 
for i in range(x): 
    for j in range(y): 
     listOfList[i][j]=input('('+str(i+1)+','+str(j+1)+'):') 
def printTable(nestedList): 
    maxLen=0 
    #this loop finds the max Length of any string in the nestedList 
    for i in range(x): 
     for j in range(y): 
      if len(nestedList[i][j])>maxLen: 
       maxLen=len(nestedList[i][j]) 
    #Loop to display table 
    for j in range(y): 
     for i in range(x): 
      print(nestedList[i][j].ljust(maxLen),sep=' ', end='') 
     print() 
printTable(listOfList) 

時出錯:

Enter the number of main items in the list: 3 
Enter the number of sub items that each list will contain: 4 
(1,1):apples 
Traceback (most recent call last): 
    File "C:\pyscripts\printTable.py", line 7, in <module> 
    listOfList[i][j]=input('('+str(i+1)+','+str(j+1)+'):') 
IndexError: list assignment index out of range 
+0

初始化列表,並使用它。您正嘗試在空列表中添加索引。我們不能在空列表中分配索引。試着初始化你會得到答案。 – Kondiba

回答

0

您需要先創建列表:

listOfList = [[0 for w in range(y)] for h in range(x)] 

輸出:

>>> x = 3 
>>> y = 4 
>>> listOfList = [[0 for w in range(y)] for h in range(x)] 
>>> listOfList 
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
0

你看你listOfList有問題

>>>len(listOfList) 
1 

>>>len(listOfList[0]) 
0 

這意味着你內部列表是空的,所以你不能訪問listOfList [0] [ 0]

>>>listOfList[0][0] 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
IndexError: list index out of range 
1

其他答案有指出你沒有在列表中預先分配空間的關鍵問題,並且試圖分配給不存在的索引會導致你得到的錯誤,但是:

你可以避免預先初始化列表從投入,如建設它在列表比較:

x = int(input('X: ')) 
y = int(input('Y: ')) 

lol = [ 
    [input('({},{}): '.format(b, a)) for a in range(1, y + 1)] 
    for b in range(1, x + 1) 
] 

然後,你可以通過使用計算不明確循環和跟蹤最大值的你最大字長:

max_length = max(len(word) for lst in lol for word in lst) 

然後,而不是循環反向索引,您可以使用zip移調行/列,並通過加入的話填充到最大長度,例如打印的每一行:

for line in zip(*lol): 
    print(' '.join(word.ljust(max_length) for word in line)) 

這給了你:

apples Alice dogs  
oranges Bob  cats  
cherries Carol moose 
banana David goose