Last active
April 14, 2016 17:34
-
-
Save youmee/c11fc99e64db540e0d4a2681a83bf9b6 to your computer and use it in GitHub Desktop.
Flatting nested lists using generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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