简体   繁体   English

遍历python中的列表

[英]Iterate through a list in python

I want to iterate through a list of lists in python. 我想遍历python中的列表列表。 I print all the values first, then subsequent iterations, I delete the last value, for example: 我先打印所有值,然后打印后续迭代,然后删除最后一个值,例如:

mylists=[["near", "belle", "round", "about"],[" vue"," bus"," stop"],["sammy"],["mombasa","road"]]

In the above list, I print: 在上面的列表中,我打印:

"near belle round about"
"near belle round"
"near belle"
"near"

and continue with all the other lists. 并继续其他所有列表。

Kindly help me with the best way to do this, I have the following code which doesn't give me what I want. 请帮助我以最好的方式做到这一点,我有以下代码并没有给我我想要的东西。

for list in sentence:

    while len(list) >0:
        print list.pop()

You're printing the return from pop , but it sounds like you want what's left after the pop . 您正在打印pop的退货,但这听起来像是您想要pop之后还剩下什么。 Try this: 尝试这个:

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

Your question title asks about doing this recursively, but your attempt wasn't recursive, and which step you intend to be recursive is somewhat unclear; 您的问题标题要求递归执行此操作,但是您的尝试不是递归的,并且您打算递归执行的步骤尚不清楚; the problem doesn't require recursion at all. 该问题根本不需要递归。

using a nested list comprehension: 使用嵌套列表理解:

[[' '.join(x[:i]) for i in range(len(x), 0, -1)] for x in mylists]

You could use print if you don't want the output: 如果不需要输出,可以使用print:

[[print(' '.join(x[:i])) for i in range(len(x), 0, -1)] for x in mylists];

nb use xrange if using python 2 如果使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM