-
Notifications
You must be signed in to change notification settings - Fork 0
/
nested_list.py
132 lines (82 loc) · 2.23 KB
/
nested_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
### append
l = [[0,1],[2,3]]
flatten_list = []
for subl in l: # 1
for item in subl: # 2
flatten_list.append(item) # 3
print(flatten_list)
### list comprehension
l = [[0,1], [2,3]]
# 3 # 1 # 2
flatten_list = [item for subl in l for item in subl]
print(flatten_list)
### lambda argument(s) : expression
flatten = lambda l: [item for subl in l for item in subl]
lst = [[3,2,1], [4,5,6], [7,8,9]]
out = flatten(lst)
print(out)
### sum
l = [[1, 2, 3], [4, 5], [6]]
l = sum(l, [])
print(l)
### operator
import operator
l = [[0,1], [2,3]]
flatlist = reduce(operator.add, l)
flatlist
### deep flattening
from iteration_utilities import deepflatten
multi_depth_list = [[0,1], [[5]], [6,4]]
flatten_list = list(deepflatten(multi_depth_list))
print(flatten_list)
### itertools
import itertools import chain
list_1 = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened
list_flat = list(chain(*list_1)) # or list(chain.from_iterable(List_1))
print(list_flat)
### reduce
from functools import reduce
multi_depth_list = [[3,2,1],[1,4,5]]
reduce(list.__add__, (list(items) for items in multi_depth_list))
### numpy ravel
import numpy as np
list1 = np.array([[3,2,1], [4,5,6], [7,8,9]])
out = list1.ravel()
print(out)
### numpy flatten
import numpy as np
lst = np.array([[3,2,1], [4,5,6], [7,8,9]])
out = lst.flatten()
print(out)
### numpy reshape
import numpy as np
lst = np.array([[3,2,1], [4,5,6], [7,8,9]])
out = lst.reshape(-1)
print(out)
### numpy flat
import numpy as np
lst = np.array([[3,2,1], [4,5,6], [7,8,9]])
print(list(lst.flat))
### numpy concatenate
import numpy as np
lst = np.array([[3,2,1], [4,5,6], [7,8,9]])
print(list(numpy.concatenate(lst)))
### reduce and concat
import functools
import operator
def functools_reduce(a):
return functools.reduce(operator.concat, a)
l = [[1, 2, 3], [4, 5], [6]]
print(functools_reduce(l))
### pandas flatten
from pandas.core.common import flatten
l = [[1,2,3], [4,5], [6]]
print(list(flatten(l)))
### matplotlib flatten
from matplotlib.cbook import flatten
l = [[1,2,3], [4,5], [6]]
print(list(flatten(l)))
### django flatten
from django.contrib.admin.utils import flatten
l = [[1,2,3], [4,5], [6]]
print(flatten(l))