python writes nested loop methods using list generation

  • 2021-01-25 07:49:24
  • OfStack

Write two nested for loops as a list generator

For example, if there is a nested list, a=[[1,2],[3,4],[5,6]], each element in the list should be extracted

Treatment with for cycle:


for i in a:
  for j in i:
    print(j)

Using the list generation:


b=[j for i in a for j in i]# Pay attention to the two for The order of 
print(b)

 b=[1, 2, 3, 4, 5, 6]

Related articles: