Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
# This file: # http://anggtwu.net/PYTHON/flatten_iterable.py.html # http://anggtwu.net/PYTHON/flatten_iterable.py # (find-angg "PYTHON/flatten_iterable.py") # Author: Eduardo Ochs <eduardoochs@gmail.com> # # (defun e () (interactive) (find-angg "PYTHON/flatten_iterable.py")) # # (find-es "sympy" "luatree-matrices") # (find-fline "~/LOGS/2024feb24.python" "https://bpa.st/B6J4K") IGNORE_TYPE = (str, bytes) def is_iterable(value): ''' Check if value is Iterable Type value: iterable return: bool Example >>> is_iterable('a') >>> is_iterable([1, 2, 3]) True >>> is_iterable(1) >>> is_iterable(None) False ''' try: iter(value) except TypeError: return False # Time: 0.000004 else: return True # Time: 0.000002 def flatten(iterable, recursive=False, ignore_type=IGNORE_TYPE): ''' Flatten First or All Layers of "iterable" Type iterable: Iterable recursive: bool ignore_type: tuple yeild: iter return: None Note version: 0.0.1 Example >>> tuple(flatten(('key', ('value',)))) ('key', 'value') >>> list(flatten( ... ['one', [b'two', b'three'], ['four', (5, (1, {'e': 'ee'}, (2, (3, ))), ['six'])]]) ... ) ['one', b'two', b'three', 'four', (5, (1, {'e': 'ee'}, (2, (3,))), ['six'])] >>> list(flatten( ... ['one', [b'two', b'three'], ['four', (5, (1, {'e': 'ee'}, (2, (3,))), ... ['six'])]], recursive=True)) ['one', b'two', b'three', 'four', 5, 1, 'e', 2, 3, 'six'] >>> list(flatten('one') >>> list(flatten('one', recursive=True) ['one'] ''' if is_iterable(iterable) and not isinstance(iterable, ignore_type): for it in iterable: if recursive: yield from flatten(it, recursive, ignore_type) elif is_iterable(it) and not isinstance(it, ignore_type): yield from it else: yield it else: # As is. yield iterable def func(*o): print(list(flatten(o))) """ * (eepitch-python) * (eepitch-kill) * (eepitch-python) exec(open("flatten_iterable.py").read(), globals()) func(1) # [1] func((1, 2)) # [1, 2] func([1, 2]) # [1, 2] """ # Local Variables: # coding: utf-8-unix # End: