def flatten(input_arr, output_arr=None): if output_arr is None: output_arr = [] for ele in input_arr: if isinstance(ele, Iterable): flatten(ele, output_arr) else: output_arr.append(ele) return output_arr
def test_flatten(self): nested_list = [2, 1, [3, [4, 5], 6], 7, [8]] flattened = flatten(nested_list) self.assertEqual(flattened, [2, 1, 3, 4, 5, 6, 7, 8]) nested_list = [[3, [4, 5], 6], 7, [8]] flattened = flatten(nested_list) self.assertEqual(flattened, [3, 4, 5, 6, 7, 8]) nested_list = [[], [8]] flattened = flatten(nested_list) self.assertEqual(flattened, [8])
def flatten_iter(iterable): """ Takes as input multi dimensional iterable and returns generator which produces one dimensional output. """ for element in iterable: if isinstance(element, Iterable): yield from flatten_iter(element) else: yield element a = [1, 2, 3, [2, 3, 5, [5, 8, 3]]] #out=[1, 2, 3, 2, 3, 5, 5, 8, 3] print(flatten(a)) c = [] for i in flatten_iter(a): #print(i) c.append(i) print(c) b = str(a) alist = [] for i in b: if i.isdigit(): alist.append(int(i)) from algorithms.arrays import flatten, flatten_iter
from algorithms.arrays import flatten if __name__ == "__main__": mydict = {"key": "test", "key2": {"key3": "value"}} mydict2 = {"a": 1, "c": {"a": 2, "b": {"x": 5, "y": 10}}, "d": [1, 2, 3]} # mydict = flatten(mydict) mydict2 = flatten(mydict2) print(mydict2)
@file: 2_Flatten.py @time: 2019/1/2 14:41 @desc: ''' from algorithms.arrays import flatten, flatten_iter from collections import Iterable def flatten_list(iterator): for ele in iterator: if isinstance(ele, Iterable): # yield from 返回迭代器的值,而yield则返回迭代器本身 yield from flatten_iter(ele) else: yield ele if __name__ == '__main__': my_list = [[7, 8], [6, 5, 4], [3, 2, 1]] result_list = flatten(my_list) iter_list = flatten_list(my_list) #print(result_list) try: for i in range(81): print(iter_list.__next__()) except StopIteration: pass #print("StopIteration")