Created
June 17, 2017 13:29
-
-
Save Pk13055/25ab89f79607db781e0e45e1f01e54b2 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
# flatten deep nested lists | |
def flatten(S): | |
if S == []: | |
return S | |
if isinstance(S[0], list): | |
return flatten(S[0]) + flatten(S[1:]) | |
return S[:1] + flatten(S[1:]) |
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
# this function recursively performs an operation on nested lists element-wise | |
import operator | |
def list_recur(l1, l2, op = operator.add): | |
if not l1: | |
return type(l1)([]) | |
elif isinstance(l1[0], type(l1)): | |
return type(l1)([list_recur(l1[0], l2[0], op)]) + list_recur(l1[1:],l2[1:], op) | |
else: | |
return type(l1)([op(l1[0], l2[0])]) + list_recur(l1[1:], l2[1:], op) |
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
# this function performs an operation element-wise on deep nested lists | |
import operator | |
def nest_operate(a, l, op = operator.add): | |
if not l: | |
return [] | |
elif isinstance(l[0], list): | |
return [nest_operate(a, l[0], op)] + nest_operate(a, l[1:], op) | |
else: | |
return [op(a, l[0])] + nest_operate(a, l[1:], op) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are a few python functions helpful for operations and manipulation of deep nested lists.