我如何遍历每个嵌套列表的内容?我显然可以在关键字中使用I,但这只是按顺序打印整个列表。我需要做的是循环遍历每个列表的内容,然后转到下一个列表并循环遍历其内容。
keywords = [
["wet","water","soaked","liquid"],
["cracked","broken","smashed","snapped"],
["dead","charge","flat","turn on"]]
for i in keywords:
print i
答案 0 :(得分:2)
试试这个:
>>> keywords = [
... ["wet","water","soaked","liquid"],
... ["cracked","broken","smashed","snapped"],
... ["dead","charge","flat","turn on"]]
>>> for i in keywords:
... for content in i:
... print content
答案 1 :(得分:2)
试试这个
for i in keywords:
for j in i:
print j
答案 2 :(得分:1)
for n in keywords:
for i in n:
print(i)
答案 3 :(得分:0)
你可以使用发电机
for i in (el for sublist in keywords for el in sublist):
print(i)
或列表理解,如果您需要保留结果并且不关心打印输出的格式
unwound = [el for sublist in keywords for el in sublist]
print(unwound)
答案 4 :(得分:0)
我就是这样做的:
keywords = [
["wet","water","soaked","liquid"],
["cracked","broken","smashed","snapped"],
["dead","charge","flat","turn on"]]
for i in range(0, len(keywords) ):
print keywords[i]
for kw in keywords[i]:
print kw
答案 5 :(得分:0)
您可以使用list comprehension
和join
方法:
print "\n".join([i for j in keywords for i in j])
wet
water
soaked
liquid
cracked
broken
smashed
snapped
dead
charge
flat
turn on
修改强>
@Pynchia建议使用generator
代替list
(IIUC):
print "\n".join(i for j in keywords for i in j)
时间:
In [188]: %timeit "\n".join([i for j in l for i in j])
1000000 loops, best of 3: 1.63 us per loop
In [189]: %timeit "\n".join(i for j in l for i in j)
1000000 loops, best of 3: 1.97 us per loop
答案 6 :(得分:0)
实际上,您可以像这样轻松访问列表中的元素:
XMPP
如果您需要通过循环访问元素,您可以编写如下代码:
print keywords[0][0] // output : "wet"