Skip to content

Instantly share code, notes, and snippets.

@Pk13055
Created June 17, 2017 13:29
Show Gist options
  • Save Pk13055/25ab89f79607db781e0e45e1f01e54b2 to your computer and use it in GitHub Desktop.
Save Pk13055/25ab89f79607db781e0e45e1f01e54b2 to your computer and use it in GitHub Desktop.
# 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 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 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)
@Pk13055
Copy link
Author

Pk13055 commented Jun 17, 2017

Here are a few python functions helpful for operations and manipulation of deep nested lists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment