I use the numpy object_ array to store variable-length strings, for example.
a = np.array(['hello','world','!'],dtype=np.object_)
Is there an easy way to find the length of the longest string in an array without looping over all elements?
max(a, key=len)gives you the longest string (and len(max(a, key=len))gives you its length) without requiring you to encode an explicit loop, but of course it maxwill execute its inner loop, since it cannot identify the "longest string" in any other way.
max(a, key=len)
len(max(a, key=len))
max
numpy dtype, () . , np.array dtype, , dtype:
In [64]: a = np.array(['hello','world','!','Oooh gaaah booo gaah?']) In [65]: a.dtype Out[65]: dtype('|S21') In [72]: a.dtype.itemsize Out[72]: 21
No, as the only place where the length of each line is known by line. Therefore, you need to know from each line what its length is.
Let's say I want to get the longest row in the second column:
data_array = [['BFNN' 'Forested bog without permafrost or patterning, no internal lawns'] ['BONS' 'Nonpatterned, open, shrub-dominated bog']] def get_max_len_column_value(data_array, column): return len(max(data_array[:,[column]], key=len)[0]) get_max_len_column_value(data_array, 1) >>>64