简体   繁体   English

遍历 list of list in Python

[英]Iterating through list of list in Python

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])]]], []]

This traverse generator function can be used to iterate over all the values:这个traverse生成器 function 可用于遍历所有值:

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'

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

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    

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”方法)

Create a method to recursively iterate through nested lists.创建一个递归迭代嵌套列表的方法。 If the current element is an instance of list, then call the same method again.如果当前元素是列表的实例,则再次调用相同的方法。 If not, print the current element.如果不是,则打印当前元素。 Here's 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)

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.制作一个 function 来遍历一个列表,如果它碰到一个也是一个列表的项目,则调用自身来迭代该成员。 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/

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)

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如果您举例说明您想对列表执行什么操作,将会有所帮助

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)
# house list of lists
house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0], 
         ["bedroom", 10.75], ["bathroom", 9.50]]
         
for key, y in house :
    print('The ' + key + ' is ' + str(y) + ' sqm ')
mylist12 = [1,2,[3,4],[5,6,7],8]

print(dir(mylist12)) # iterable


for i in mylist12:
    if (isinstance(i,list)):
        for j in i:
            print(j)
    else:
            print(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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