Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created April 13, 2018 00:33
Show Gist options
  • Save shiracamus/675365b98251bfe16540ed6d67fca006 to your computer and use it in GitHub Desktop.
Save shiracamus/675365b98251bfe16540ed6d67fca006 to your computer and use it in GitHub Desktop.
#!/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