处理多级列表(2)

时间:2013-04-04 10:01:06

标签: python list

假设我有一个列表:

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']

如何实现以(elem, indexes)

的形式产生元组的函数
  • elem是元素
  • indexes是达到该元素所需的索引。

示例:

>>> for x in my_func(li):
    print x
('0', [0])
('1', [1, 0])
('2', [1, 1])
('3', [2, 0])
('4', [2, 1, 0])
('5', [2, 1, 1])
('6', [2, 2])
('7', [2, 3, 0])
('8', [2, 4])
('9', [3])

3 个答案:

答案 0 :(得分:5)

这是一个嵌套版本

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            yield list(to_int(j, path+[i]))
        else:
            yield int(j), path+[i]

print(list(to_int(li)))

扁平版(Python3.3 +)

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            yield from to_int(j, path+[i])
        else:
            yield int(j), path+[i]

for item in to_int(li):
    print (item)

如果你不能使用yield from(< Python3.3),你必须用这种麻烦的方式写它

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            for item in to_int(j, path+[i]): yield item
        else:
            yield int(j), path+[i]

for item in to_int(li):
    print (item)

注意,通常将空列表作为默认参数是一个坏主意,但在这里我们注意不要改变它,所以没关系。

答案 1 :(得分:1)

def nextedindex(lst, indice=tuple()):
    for index, data in enumerate(lst):
        if isinstance(data, collections.Sequence):
            for next in nestedindex(data, indice + (index,)): yield next
        else:
            yield indice + (index,), data

答案 2 :(得分:1)

一个简单的递归版本。

这个循环遍历列表的每个级别,跟踪索引路径以到达currentIndex中的当前循环。

def indexRecursive(alist, currentIndex, tuples):
    i = 0
    for item in alist:
        if type(item) != list:
           tuples.append((item, currentIndex + [i]))
        else:
            indexRecursive(alist[i], currentIndex + [i], tuples)
        i += 1

li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
tuplesList = []
indexRecursive(li, [], tuplesList)
print tuplesList