Python遍历嵌套列表

时间:2020-06-25 05:38:38

标签: python list function for-loop

例如,我试图遍历嵌套列表:

[['1', '2', '3', '4', '5'], ['6', '7', '8'], ['9', '10']]

我想要的输出是

[['1', '2'], ['2', '3'], ['3', '4'], ['4', '5'], ['6', '7'], ['7', '8'], ['9', '10']]

我已经能够使用函数为我提供第一个列表的结果

[['1', '2'], ['2', '3'], ['3', '4'], ['4', '5']]

,但是无法遍历所有嵌套列表。我敢肯定我可以添加一个简单的循环,但是我无法使它正常工作。

4 个答案:

答案 0 :(得分:2)

您可以使用zip ping来获取配对,然后使用chain进行串联:

from itertools import chain
data = [['1', '2', '3', '4', '5'], ['6', '7', '8'], ['9', '10']]
result = list(chain.from_iterable(zip(x, x[1:]) for x in data))

答案 1 :(得分:1)

您可以尝试以下方法:

output = []
for i in l:    
    for index,j in enumerate(i):
        if len(i) != index+1:
            output.append([j,i[index+1]])    
output

输出为:

[['1', '2'],
 ['2', '3'],
 ['3', '4'],
 ['4', '5'],
 ['6', '7'],
 ['7', '8'],
 ['9', '10']]

答案 2 :(得分:0)

my_list = [['1', '2', '3', '4', '5'], ['6', '7', '8'], ['9', '10']]
def my_func (curr_list):
    return [[curr_list[i-1], curr_list[i]] for i in range(1, len(curr_list))]
ret = []
for i in [my_func(i) for i in my_list]: ret += i
print(ret)
[['1', '2'], ['2', '3'], ['3', '4'], ['4', '5'], ['6', '7'], ['7', '8'], ['9', '10']]

答案 3 :(得分:0)

获取可迭代的序列

def chain(lst):
    for sequence in lst:
        for index in range(len(sequence)-1):
            yield sequence[index:index+2]

lst = [['1', '2', '3', '4', '5'], ['6', '7', '8'], ['9', '10']]

print(list(chain(lst)))