迭代Python中的列表列表

时间:2021-02-16 22:30:31

I want to iterate through list of list.
I want to iterate through irregularly nested lists inside list also.
Can anyone let me know how can I do that?

我想遍历列表列表。我想迭代列表中的不规则嵌套列表。任何人都可以让我知道我该怎么做?

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]

9 个解决方案

#1


40  

This traverse generator function can be used to iterate over all the values:

此遍历生成器函数可用于迭代所有值:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

#2


29  

So wait, this is just a list-within-a-list?

等等,这只是一个列表中的列表?

The easiest way is probably just to use nested for loops:

最简单的方法可能就是使用嵌套for循环:

>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
...     for number in list:
...         print number
...
1
3
4
2
4
4
3
4
5

Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.

或者它比那更复杂?任意嵌套还是什么?如果还有别的东西,请告诉我们。

Also, for performance reasons, you might want to look at using list comprehensions to do this:

此外,出于性能原因,您可能希望使用列表推导来执行此操作:

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

#3


12  

This can also be achieved with itertools.chain.from_iterable which will flatten the consecutive iterables:

这也可以通过itertools.chain.from_iterable来实现,这将使连续的迭代变平:

import itertools
for item in itertools.chain.from_iterable(iterables):
    # do something with item    

#4


6  

if you don't want recursion you could try:

如果你不想要递归,你可以试试:

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
    for i in layer1:
        if isinstance(i,list):
            for j in i:
                layer2.append(j)
        else:
            print i
    layer1[:]=layer2
    layer2=[]
    if len(layer1)==0:
        break

which gives:

这使:

sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one

(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)

(请注意,它没有查看列表的元组,因为元组不是列表。如果要修复此问题,可以将元组添加到“isinstance”方法中)

#5


4  

It sounds like you need to use recursion. Make a function to iterate through a list, and if it hits an item that is also a list, call itself to iterate on the member. Here's a link to something similar:

听起来你需要使用递归。创建一个迭代列表的函数,如果它遇到一个也是列表的项,则调用自己迭代该成员。这是类似的链接:

http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/

http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/

#6


4  

If you wonder to get all values in the same list you can use the following code:

如果您想要在同一个列表中获取所有值,可以使用以下代码:

text = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]

def get_values(lVals):
    res = []
    for val in lVals:
        if type(val) not in [list, set, tuple]:
            res.append(val)
        else:
            res.extend(get_values(val))
    return res

get_values(text)

#7


1  

two nested for loops?

两个嵌套for循环?

 for a in x:
     print "--------------"
     for b in a:
             print b

It would help if you gave an example of what you want to do with the lists

如果你举例说明你想对列表做些什么会有所帮助

#8


1  

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
output = []

def lister(l):
    for item in l:
        if type(item) in [list, tuple, set]:
            lister(item)
        else:
            output.append(item)

lister(x)

#9


0  

Create a method to iterate through nested lists. If the current element is instance of the list then again call same method. Have an example.

创建一个迭代嵌套列表的方法。如果当前元素是列表的实例,则再次调用相同的方法。举个例子。

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)

#1


40  

This traverse generator function can be used to iterate over all the values:

此遍历生成器函数可用于迭代所有值:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

#2


29  

So wait, this is just a list-within-a-list?

等等,这只是一个列表中的列表?

The easiest way is probably just to use nested for loops:

最简单的方法可能就是使用嵌套for循环:

>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
...     for number in list:
...         print number
...
1
3
4
2
4
4
3
4
5

Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.

或者它比那更复杂?任意嵌套还是什么?如果还有别的东西,请告诉我们。

Also, for performance reasons, you might want to look at using list comprehensions to do this:

此外,出于性能原因,您可能希望使用列表推导来执行此操作:

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

#3


12  

This can also be achieved with itertools.chain.from_iterable which will flatten the consecutive iterables:

这也可以通过itertools.chain.from_iterable来实现,这将使连续的迭代变平:

import itertools
for item in itertools.chain.from_iterable(iterables):
    # do something with item    

#4


6  

if you don't want recursion you could try:

如果你不想要递归,你可以试试:

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
    for i in layer1:
        if isinstance(i,list):
            for j in i:
                layer2.append(j)
        else:
            print i
    layer1[:]=layer2
    layer2=[]
    if len(layer1)==0:
        break

which gives:

这使:

sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one

(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)

(请注意,它没有查看列表的元组,因为元组不是列表。如果要修复此问题,可以将元组添加到“isinstance”方法中)

#5


4  

It sounds like you need to use recursion. Make a function to iterate through a list, and if it hits an item that is also a list, call itself to iterate on the member. Here's a link to something similar:

听起来你需要使用递归。创建一个迭代列表的函数,如果它遇到一个也是列表的项,则调用自己迭代该成员。这是类似的链接:

http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/

http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/

#6


4  

If you wonder to get all values in the same list you can use the following code:

如果您想要在同一个列表中获取所有值,可以使用以下代码:

text = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]

def get_values(lVals):
    res = []
    for val in lVals:
        if type(val) not in [list, set, tuple]:
            res.append(val)
        else:
            res.extend(get_values(val))
    return res

get_values(text)

#7


1  

two nested for loops?

两个嵌套for循环?

 for a in x:
     print "--------------"
     for b in a:
             print b

It would help if you gave an example of what you want to do with the lists

如果你举例说明你想对列表做些什么会有所帮助

#8


1  

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
output = []

def lister(l):
    for item in l:
        if type(item) in [list, tuple, set]:
            lister(item)
        else:
            output.append(item)

lister(x)

#9


0  

Create a method to iterate through nested lists. If the current element is instance of the list then again call same method. Have an example.

创建一个迭代嵌套列表的方法。如果当前元素是列表的实例,则再次调用相同的方法。举个例子。

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)