Python Longest String in NumPy Array
To seek out the longest string in a given NumPy array, say arr
, you should utilize the max(arr, key=len)
perform that determines the utmost by evaluating the size of the array components utilizing the len()
perform as a key for comparability.
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) print(max(arr, key=len)) # Alice
You’ll find extra concerning the highly effective max()
perform in our detailed weblog tutorial:
👉 Beneficial Tutorial: Python Most Perform
Python Size of Longest String in NumPy Array
To seek out the size of the longest string in a NumPy array arr
, use the max(arr, key=len)
perform to acquire the string with the utmost size after which move this max string into the len()
perform to acquire the variety of characters of the max string.
len(max(arr, key=len))
Right here’s a extra detailed code instance of a easy 1D NumPy Array:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String: print(max(arr, key=len)) # Alice # Print Size of Longest String print(len(max(arr, key=len))) # 5
Get Longest String from NumPy Axis (2D, Column or Row)
To get the longest string from a sure NumPy array axis (e.g., row or column), first use easy NumPy slicing and indexing to get that axis (e.g., arr[0, :]
to get the primary row) and move it into the max()
perform with the key
argument set to the size perform like so: max(arr[0, :], key=len)
.
Right here’s an instance to get the longest string of the first row of a 2D array:
import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len)) # Alice
Right here’s an instance to get the longest string of the third column of a 2D array:
print(max(arr[:, 2], key=len)) # Leonard
You get the concept. 🙂
If you wish to get the longest string from the entire NumPy array, not solely from a column or row or axis, first flatten it after which move the flattened array into the max()
perform utilizing the key=len
argument.
👉 Beneficial Tutorial: Flatten a NumPy Array?
Whereas working as a researcher in distributed methods, Dr. Christian Mayer discovered his love for educating pc science college students.
To assist college students attain increased ranges of Python success, he based the programming training web site Finxter.com. He’s writer of the favored programming e-book Python One-Liners (NoStarch 2020), coauthor of the Espresso Break Python sequence of self-published books, pc science fanatic, freelancer, and proprietor of one of many prime 10 largest Python blogs worldwide.
His passions are writing, studying, and coding. However his biggest ardour is to serve aspiring coders by Finxter and assist them to spice up their abilities. You possibly can be part of his free e mail academy right here.