4 回答

TA貢獻1827條經驗 獲得超8個贊
您可以遍歷列表列表并訪問所需索引處的每個內部列表:
my_index = <some integer>
for item in lists_of_lists:
doSomething(item[my_index])

TA貢獻1793條經驗 獲得超6個贊
如果您有包含相同信息的內部列表,并且您只想在第一個內部進行迭代,請執行以下操作:
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],]
# iterate on 1,2,3,4
for item in list_of_lists[0]: # list_of_lists[0] is the 1st inner list
doSomething(item)
# iterate on 2,2,2,2
for inner_list in list_of_lists:
doSomething(inner_list[1])

TA貢獻1966條經驗 獲得超4個贊
使用 numpy 數組,您的代碼將起作用。
使用列表,您應該這樣做:
# Some test data
list_of_lists = [
[ 0, 1, 2, 3 ],
[ 10, 11, 12 ,13 ],
[ 20, 21, 22, 23 ],
[ 30, 31, 32, 33 ]
]
index = 2 # the sublists index you want to iterate on
for item in ( sublist[index] for sublist in list_of_lists ):
#doSomething() # Commented out for the demonstration to work
print(item) # A print to see the values of item that you can remove
輸出 :
2
12
22
32
這將遍歷生成器,my_index為 中的每個子列表生成項目 at list_of_lists。
請注意,您可以在任何需要迭代的地方使用生成器。
(我假設doSomething()只是您的“有用代碼”的占位符,如果不是,則項目不會傳遞給函數)

TA貢獻1818條經驗 獲得超8個贊
如果您要多次對列而不是行進行操作,請考慮轉置數據,例如:
list_of_lists = [[1,2,3],[4,5,6]]
transposed = list(zip(*list_of_lists))
print(transposed) # [(1, 4), (2, 5), (3, 6)]
for item in transposed[1]:
print(item)
輸出:
2
5
請注意,此解決方案僅在您不打算更改list_of_lists
添加回答
舉報