[英]Iterate through a list in python
我想遍历python中的列表列表。 我先打印所有值,然后打印后续迭代,然后删除最后一个值,例如:
mylists=[["near", "belle", "round", "about"],[" vue"," bus"," stop"],["sammy"],["mombasa","road"]]
在上面的列表中,我打印:
"near belle round about"
"near belle round"
"near belle"
"near"
并继续其他所有列表。
请帮助我以最好的方式做到这一点,我有以下代码并没有给我我想要的东西。
for list in sentence:
while len(list) >0:
print list.pop()
您正在打印pop
的退货,但这听起来像是您想要pop
之后还剩下什么。 尝试这个:
for alist in mylists: # Use alist, not list, to avoid shadowing list built-in
while alist: # Faster equivalent to while len(alist) > 0:
print(' '.join(alist)) # Join and print current value
alist.pop() # Remove last, finished when emptied
您的问题标题要求递归执行此操作,但是您的尝试不是递归的,并且您打算递归执行的步骤尚不清楚; 该问题根本不需要递归。
使用嵌套列表理解:
[[' '.join(x[:i]) for i in range(len(x), 0, -1)] for x in mylists]
如果不需要输出,可以使用print:
[[print(' '.join(x[:i])) for i in range(len(x), 0, -1)] for x in mylists];
如果使用python 2,请使用xrange
for list in mylists: #iterator for outer list
while len(list) >0: #iterator for inner list , length of inner list > 0
print list #print elements in the inner list
list.pop() #pop the last element of the inner list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.