The nested_tools library in Python
$ pip install nestedtools
import nested_tools as nt
l = [['foo', 'bar'], 'baz']
print(nt.index(l, 'bar'))
Output: (0, 1)
print(nt.get(l, (0, 1)))
Output: bar
print(list(nt.flatten(l)))
Output: ['foo', 'bar', 'baz']
old_list = ['A', 'B', 'C', 'D', 'E', 'F']
new_shape = [[0], [1, 2], [3, [4, 5]]]
print(list(nt.transpose(old_list, new_shape)))
Output: [['A'], ['B', 'C'], ['D', ['E', 'F']]]
l = [['A'], ['B', 'C'], ['D', ['E', 'F']]]
print(list(nt.to_shape(l)))
Output: [[0], [1, 2], [3, [4, 5]]]
a = [['foo', 'bar'], 'baz']
b = ['A', ['B', ['C']]]
print(list(nt.make_same_shape(a, b)))
Output: ['foo', ['bar', ['baz']]]
l = [{1, 2, (3,)}, [4, {5}, (6,)]]
print(list(nt.convert_all(l)))
Output: [[1, 2, [3]], [4, [5], [6]]]
convert_all
takes two more optional parameters
to
- a type to convert to (default =list
):
print(tuple(nt.convert_all(l, tuple)))
Output: ((1, 2, (3,)), (4, (5,), (6,)))
exclude
- a tuple of any iterable types to not convert (default =(str,)
):
print(list(nt.convert_all(l, exclude=(set,))))
Output: [{1, 2, (3,)}, [4, {5}, [6]]]