簡體   English   中英

Python 循環遍歷嵌套列表

[英]Python looping through nest lists

例如,我正在嘗試遍歷嵌套列表:

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

我想要的 output 是

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

我已經能夠使用 function 給我第一個列表的結果

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

但無法遍歷所有嵌套列表。 我確信我可以添加一個簡單的循環,但我無法讓一個循環工作。

您可以使用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))

你可以試試這個:

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

output 是:

[['1', '2'],
 ['2', '3'],
 ['3', '4'],
 ['4', '5'],
 ['6', '7'],
 ['7', '8'],
 ['9', '10']]
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']]

獲取可迭代序列

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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM