Created
April 13, 2018 00:33
-
-
Save shiracamus/675365b98251bfe16540ed6d67fca006 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
def flatten(data, depth=-1): | |
""" | |
flatten(data) -> list | |
flatten(data, depth) -> list | |
Return flatted data of list or tupple as list. | |
>>> data = [[1, 2], [3, [4, 5, [6]]]] | |
>>> flatten(data) | |
[1, 2, 3, 4, 5, 6] | |
>>> flatten(data, 0) | |
[[1, 2], [3, [4, 5, [6]]]] | |
>>> flatten(data, 1) | |
[1, 2, 3, [4, 5, [6]]] | |
>>> flatten(data, 2) | |
[1, 2, 3, 4, 5, [6]] | |
>>> flatten(data, 3) | |
[1, 2, 3, 4, 5, 6] | |
""" | |
return [element | |
for item in data | |
for element in (flatten(item, depth - 1) | |
if depth != 0 and hasattr(item, '__iter__') | |
else [item]) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment