Reputation: 19
I have a list of lists which I converted into a numpy array:
lsts = ([[1,2,3], ['a','b','a']],
[[4,5,6,7], ['a','a','b','b']],
[[1,2,3],['b','a','b']])
np_lsts = np.array(lsts)
I want to return the largest element in the first list where a 'b' occurs in the second list. I think I have to use indexes but am stuck!
i.e. I want to return (2, 7, 3) in this case
Upvotes: 0
Views: 93
Reputation: 8464
That will do:
[max(u for u,v in zip(x,y) if v=='b') for x,y in lsts if 'b' in y]
Using zip()
and max()
in a nested list comprehension
Upvotes: 1
Reputation: 9863
One possible solution to your problem:
lsts = ([[1, 2, 3], ['a', 'b', 'a']],
[[4, 5, 6, 7], ['a', 'a', 'b', 'b']],
[[1, 2, 3], ['b', 'a', 'b']],
[[1, 2, 3], ['a']]
)
result = []
for l in lsts:
indices = [l[0][index] for index, v in enumerate(l[1]) if v == 'b']
if indices:
result.append(max(indices))
print result
Upvotes: 1
Reputation: 10759
This should be a lot more efficient than the current solutions if the sublists have a lot of elements, since it is vectorized over those sublists:
import numpy_indexed as npi
results = [npi.group_by(k).max(v) for v,k in lsts]
Upvotes: 0
Reputation: 1779
def get_max(l):
first = True
for e1, e2 in zip(l[0], l[1]):
if e2 == 'b' and first:
max = e1
first = False
elif e2 == 'b' and e1 > max:
max = e1
return max
result = ()
for l in lsts:
if 'b' in l[1]:
result += (get_max(l),)
print(result)
Upvotes: 0
Reputation: 1681
The following function returns a result
list. If needed, you could return a tuple instead of a list.
def maxNum(lsts, character):
result = []
for entry in lsts:
if character in entry[1]:
result.append(max(entry[0]))
return result
# lsts = ... # (put lsts here)
print maxNum(lsts, 'b')
Upvotes: 1