Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- mylist_regular = [[1, 2, [3]], 4]
- mylist_recursive = [[1, 2, [3]], 4]
- # flatten a list of lists of integers, recursively
- # lst : list of integers
- # returns: a flattened list
- def flatten_recursive(lst):
- # return the current element if it's not a list, else call routine again with current list
- # initial value is empty list
- return sum(([x] if not isinstance(x, list) else flatten_recursive(x) for x in lst), [])
- # flatten a list of lists of integers, recursively
- # lst : list of integers, unpacked in positional params
- # returns: the next interger from the list
- def flatten_regular(*lst):
- for x in lst:
- print(x)
- if hasattr(x, '__iter__'):
- # if this is another list (it's iterable), unpack it and
- for y in flatten_regular(*x):
- # yield each value upon invocation
- yield y
- else:
- # if it's not iterable (not a list), yield the intermediate value
- yield x
- print(flatten_recursive(mylist_recursive))
- # convert the result back into a list
- print(list(flatten_regular(mylist_regular)))
Add Comment
Please, Sign In to add comment