Home > database >  Index of array with maximum length
Index of array with maximum length

Time:02-01

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!

CodePudding user response:

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

CodePudding user response:

You can use enumerate and max for this one:

max_length_index, _ = max(enumerate(l), key=lambda index, lst  : len(lst))

CodePudding user response:

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)))

CodePudding user response:

The fix to your code is this

    feature_len = len(feature)
    if feature_len > max_len:
        max_len = feature_len  # <-- store the max so you can check the next one
        index = i # <-- store the index

A oneliner would look like this

from operator import itemgetter
max([(i, len(f)) for i, f in enumerate(features)], key=itemgetter(1))[0]

To understand it read the following code.

max(
    [
        (index, len(feature))
        for index, feature in enumerate(
            features
        )
    ],
    key=itemgetter(1),
)[0]
  •  Tags:  
  • Related