def test_flatten_iter(self): nested_list = [2, 1, [3, [4, 5], 6], 7, [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 2) self.assertEqual(next(flattened), 1) self.assertEqual(next(flattened), 3) self.assertEqual(next(flattened), 4) self.assertEqual(next(flattened), 5) self.assertEqual(next(flattened), 6) self.assertEqual(next(flattened), 7) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened) nested_list = [[3, [4, 5], 6], 7, [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 3) self.assertEqual(next(flattened), 4) self.assertEqual(next(flattened), 5) self.assertEqual(next(flattened), 6) self.assertEqual(next(flattened), 7) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened) nested_list = [[], [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened)
def test_flatten_iter(self): nested_list = [2, 1, [3, [4, 5], 6], 7, [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 2) self.assertEqual(next(flattened), 1) self.assertEqual(next(flattened), 3) self.assertEqual(next(flattened), 4) self.assertEqual(next(flattened), 5) self.assertEqual(next(flattened), 6) self.assertEqual(next(flattened), 7) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened) nested_list = [[3, [4, 5], 6], 7, [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 3) self.assertEqual(next(flattened), 4) self.assertEqual(next(flattened), 5) self.assertEqual(next(flattened), 6) self.assertEqual(next(flattened), 7) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened) nested_list = [[], [8]] flattened = flatten_iter(nested_list) self.assertEqual(next(flattened), 8) self.assertRaises(StopIteration, next, flattened)
def flatten_list(iterator): for ele in iterator: if isinstance(ele, Iterable): # yield from 返回迭代器的值,而yield则返回迭代器本身 yield from flatten_iter(ele) else: yield ele
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
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 a = [1, 2, 3, [2, 3, 5, [5, 8, 3]]] #out=[1, 2, 3, 2, 3, 5, 5, 8, 3]