Skip to content

Instantly share code, notes, and snippets.

@youmee
Last active April 14, 2016 17:34
Show Gist options
  • Save youmee/c11fc99e64db540e0d4a2681a83bf9b6 to your computer and use it in GitHub Desktop.
Save youmee/c11fc99e64db540e0d4a2681a83bf9b6 to your computer and use it in GitHub Desktop.
Flatting nested lists using generators
# coding: utf-8
import unittest
def flat_list(input_list):
def flatten(lst):
for i in lst:
if isinstance(i, list):
for j in flatten(i):
yield j
else:
yield i
return list(flatten(input_list))
class TestFlattingMethod(unittest.TestCase):
def setUp(self):
self.lists = [
[
[[1, 2, [3]], 4],
[1, 2, 3, 4]
],
[
[[4, 6], [5, 5], [6, 7]],
[4, 6, 5, 5, 6, 7],
],
[
[6, 3, [3], 12, [[[32], 43], 1], 0],
[6, 3, 3, 12, 32, 43, 1, 0],
]
]
def test_flatten_method(self):
for lst in self.lists:
self.assertEqual(flat_list(lst[0]), lst[1])
print('OK: flat_list {} == {}'.format(lst[0], lst[1]))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment