1

I am trying to get the index of the array with the longest length. I have this array of arrays.

[
 [0,7,3],
 [1],
 [2,6,5,2,9],
 [1,2]
]

The desired outcome is 2 because it is the array with the maximum length. I have this working code:

max_len = -1
index = -1

for i, feature in enumerate(features):
    if max_len < len(feature):
        max_len = len(feature)
        index = I

print(index)

I think that should be a one-liner or a much better and simpler way to do it. Does anyone know a better way to do it?

Thanks!

3 Answers 3

3

That looks like a python list, not a numpy array. You can use l.index(max(l, key=len)) if l is your list.

Sign up to request clarification or add additional context in comments.

3 Comments

This is not very efficient. You are iterating the list 2 times. One in index() call and other is in max call.
@ShipluMokaddim it is much more efficient than pulling from the enumerate iterator and calling a python lambda for each element. Time it yourself.
@timgeb - benchmarked both solutions with 1000 to 100_000 lists of length 4 to 1000. This solution is ~5x faster.
0

This is a one-liner:

vals = [[0,7,3],[1],[2,6,5,2,9],[1,2]]
pd.Series(vals).apply(lambda x: len(x)).idxmax()

You could also do this without pandas:

lens = [len(val) for val in vals]
print(lens.index(max(lens)))

Comments

0

You can use enumerate and max for this one:

max_length_index, _ = max(enumerate(l), key=lambda index_and_lst  : len(index_and_lst[1]))

2 Comments

The key function expects one parameter
@timgeb Indeed, looks like I cannot use unrolling here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.