2017-02-16 432 views
-1

我目前正在嘗試循環並從列表中打印特定值。 我試圖做到這一點的方式就是這樣。如何使用for循環來循環遍歷Python中的嵌套列表

for i in range(len(PrintedList)): 
    index = i 
    elem=PrintedList[i] 
    print(elem) 
    print ("Product = ", PrintedList [index,1], "price £",PrintedList [index,2]) 

然而,這返回的錯誤:

TypeError: list indices must be integers or slices, not tuple. 

我真的不確定該怎麼做才能解決這個問題。

+0

發佈輸出(或小樣本)'print(Pri ntedList)',所以我們可以看看實際的結構。我們不能通過查看不起作用的代碼來猜測=) – slezica

+0

你可能指的是'PrintledList [index] [1]'和'PrintedList [index] [2]'? – TidB

回答

0

當您引用一個嵌套列表時,引用每個括號中的索引。試試這個:

for i in range(len(PrintedList)): 
    index = i 
    elem=PrintedList[i] 
    print(elem) 
    print ("Product = ", PrintedList [index][1], "price £",PrintedList [index][2]) 
+0

非常感謝! – PuzzledByPython

4

請不要迭代使用indeces,這是醜陋的,並認爲是非pythonic。除了直接遍歷列表本身和使用的元組分配,即:

for product, price, *rest in PrintedList: 
    print ("Product = ", product, "price £", price) 

for elem in PrintedList: 
    product, price, *rest = elem 
    print ("Product = ", product, "price £", price) 

*rest只要求如果某些子列表包含多於2項(價格和產品)

如果你需要使用枚舉,使用枚舉:

for index, (product, price, *rest) in enumerate(PrintedList): 
    print (index, "Product = ", product, "price £", price) 
+0

絕對是更pythonic的方式來做到這一點,我只是試圖解決代碼中的具體錯誤。 + 1爲休息,我不知道這一點。 – SgtStens