如何在 Python 中逐行打印嵌套列表中的项目?
How do you print the items in a nested list line by line in Python?
例如,如果我有:
l = [["apple", "orange", "banana"], ["grape", "strawberry", "raspberry"]]
我希望它能打印出来:
["apple", "orange", "banana"]
["grape", "strawberry", "raspberry"]
而不是:
[["apple", "orange", "banana"], ["grape", "strawberry", "raspberry"]]
有什么简单的方法吗?
使用 for
循环并遍历列表中的每个项目:
for item in l:
print item
您的任务是尽可能多地分解嵌套数组。
for i in arr:
print(i)
但假设您有一个双层嵌套数组。
你可以这样做:
for i in arr:
for inArr in i:
print(i)
如果您有一个三重嵌套并想打印每个,您就可以了。
for i in arr:
for inArr in i:
for subArr in inArr:
print(subArr)
我们为每个索引使用一个 foreach,然后继续使用 foreach 来查看更深的索引。
I know you only asked for the first one, but I wanted to give a unique
and in depth answer.
例如,如果我有:
l = [["apple", "orange", "banana"], ["grape", "strawberry", "raspberry"]]
我希望它能打印出来:
["apple", "orange", "banana"]
["grape", "strawberry", "raspberry"]
而不是:
[["apple", "orange", "banana"], ["grape", "strawberry", "raspberry"]]
有什么简单的方法吗?
使用 for
循环并遍历列表中的每个项目:
for item in l:
print item
您的任务是尽可能多地分解嵌套数组。
for i in arr:
print(i)
但假设您有一个双层嵌套数组。 你可以这样做:
for i in arr:
for inArr in i:
print(i)
如果您有一个三重嵌套并想打印每个,您就可以了。
for i in arr:
for inArr in i:
for subArr in inArr:
print(subArr)
我们为每个索引使用一个 foreach,然后继续使用 foreach 来查看更深的索引。
I know you only asked for the first one, but I wanted to give a unique and in depth answer.