Update
To get rid of the for
loop (which I used because the program would be more efficient with a break
statement in place), you can use the itertools.takewhile()
method to act as a break
statement within the list comprehension, thus making the program more efficient (I tested 2 versions of the code, one with the itertools.takewhile()
method and one without; the former turned out faster):
import numpy as np
from itertools import groupby, takewhile
a = np.array([[193, 64, 64, 139, 180, 180, 104, 152, 69, 22, 192, 92],
[ 1, 36, 156, 152, 152, 37, 46, 143, 141, 114, 25, 134],
[110, 96, 52, 53, 35, 147, 3, 116, 20, 11, 137, 5]])
result = [[k[0] for i, k in takewhile(lambda x: x[0] != 5, enumerate(groupby(row)))] for row in a]
print(np.array(result))
Output:
[[193 64 139 180 104]
[ 1 36 156 152 37]
[110 96 52 53 35]]
(Using for
loops)
You can try using the built-in enumerate()
function along with the itertools.groupby()
method:
import numpy as np
from itertools import groupby
a = np.array([[193, 64, 64, 139, 180, 180, 104, 152, 69, 22, 192, 92],
[ 1, 36, 156, 152, 152, 37, 46, 143, 141, 114, 25, 134],
[110, 96, 52, 53, 35, 147, 3, 116, 20, 11, 137, 5]])
def get_unique(a, amt):
for row in a:
r = []
for i, k in enumerate(groupby(row)):
if i == amt:
break
r.append(k[0])
yield r
for row in get_unique(a, 5):
print(row)
Output:
[193, 64, 139, 180, 104]
[1, 36, 156, 152, 37]
[110, 96, 52, 53, 35]
Omitting the function:
import numpy as np
from itertools import groupby
a = np.array([[193, 64, 64, 139, 180, 180, 104, 152, 69, 22, 192, 92],
[ 1, 36, 156, 152, 152, 37, 46, 143, 141, 114, 25, 134],
[110, 96, 52, 53, 35, 147, 3, 116, 20, 11, 137, 5]])
result = []
for row in a:
r = []
for i, k in enumerate(groupby(row)):
if i == 5:
break
r.append(k[0])
result.append(r)
print(np.array(result))
Output:
[[193 64 139 180 104]
[ 1 36 156 152 37]
[110 96 52 53 35]]