Use python generators and recursive two-dimensional or even multidimensional list is converted into one-dimensional list

first question:

Arbitrary two-dimensional list into a one-dimensional list:

a = [[1,2,3,4],[6,8,9,6]]

def fun1(a):
	for i in a:
		for j in i:
			yield j

print(list(fun1(a)))
#输出为:[1,2,3,4,6,8,9,6]

Since the generator can be used to achieve convert any two-dimensional list is a list of one-dimensional function;
so, considered in conjunction with the use of recursive generators to achieve any multidimensional lists into one-dimensional list:

The second question:

Convert any multidimensional list is one-dimensional list:

b = [1,2,34,[3,1,54,[1223,432,[3,6,2]]],[3,5,2,[3,4,2]],[1,2,3]]

def fun2(b):
	try:
		for i in b:
			for j in fun2(i):
				yield j
	except TypeError:
		yield b

print(list(fun2(b)))
#输出为:[1, 2, 34, 3, 1, 54, 1223, 432, 3, 6, 2, 3, 5, 2, 3, 4, 2, 1, 2, 3]
Published 65 original articles · won praise 50 · views 3591

Guess you like

Origin blog.csdn.net/qq_44907926/article/details/104739943