Python 列表生成式

it2026-08-31  4

使用列表生成式表示两个嵌套for循环

for循环处理 TestList = [[1,2,3], [4,5,6], [7,8,9]] temp = [] for i in TestList: for j in i: temp.append(j) print(temp) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] 列表生成式 temp = [j for i in TestList for j in i] print(temp) >> [1, 2, 3, 4, 5, 6, 7, 8, 9]

注意两个for循环的顺序!!!

最新回复(0)