訪問巢狀列表中的值

從三維列表開始:

alist = [[[1,2],[3,4]], [[5,6,7],[8,9,10], [12, 13, 14]]]

訪問列表中的專案:

print(alist[0][0][1])
#2
#Accesses second element in the first list in the first list

print(alist[1][1][2])
#10
#Accesses the third element in the second list in the second list

執行支援操作:

alist[0][0].append(11)
print(alist[0][0][2])
#11
#Appends 11 to the end of the first list in the first list

使用巢狀 for 迴圈列印列表:

for row in alist: #One way to loop through nested lists
    for col in row:
        print(col)
#[1, 2, 11]
#[3, 4]
#[5, 6, 7]
#[8, 9, 10]
#[12, 13, 14]

請注意,此操作可用於列表推導,甚至可用作生成器以提高效率,例如:

[col for row in alist for col in row]
#[[1, 2, 11], [3, 4], [5, 6, 7], [8, 9, 10], [12, 13, 14]]

並非外部列表中的所有專案都必須是列表本身:

alist[1].insert(2, 15)
#Inserts 15 into the third position in the second list

另一種使用巢狀 for 迴圈的方法。另一種方式更好但我偶爾需要使用它:

for row in range(len(alist)): #A less Pythonic way to loop through lists
    for col in range(len(alist[row])):
       print(alist[row][col])

#[1, 2, 11]
#[3, 4]
#[5, 6, 7]
#[8, 9, 10]
#15
#[12, 13, 14]

在巢狀列表中使用切片:

print(alist[1][1:])
#[[8, 9, 10], 15, [12, 13, 14]]
#Slices still work

最終名單:

print(alist)
#[[[1, 2, 11], [3, 4]], [[5, 6, 7], [8, 9, 10], 15, [12, 13, 14]]]