![]() |
|
[Tut] How to Find the Longest String in a NumPy Array? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Find the Longest String in a NumPy Array? (/thread-99964.html) |
[Tut] How to Find the Longest String in a NumPy Array? - xSicKxBot - 09-19-2022 How to Find the Longest String in a NumPy Array? 5/5 – (1 vote) Python Longest String in NumPy Array To find the longest string in a given NumPy array, say Code: arrCode: max(arr, key=len)Code: len()Code: import numpy as np arr = np.array(['Alice', 'Bob', 'Carl'])
print(max(arr, key=len))
# AliceYou can find more about the powerful Code: max() Recommended Tutorial: Python Maximum FunctionPython Length of Longest String in NumPy Array To find the length of the longest string in a NumPy array Code: arrCode: max(arr, key=len)Code: len()Code: len(max(arr, key=len))Here’s a more detailed code example of a simple 1D NumPy Array: Code: import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String:
print(max(arr, key=len))
# Alice # Print Length of Longest String
print(len(max(arr, key=len)))
# 5To get the longest string from a certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g., Code: arr[0, :]Code: max()Code: keyCode: max(arr[0, :], key=len)Here’s an example to get the longest string of the first row of a 2D array: Code: import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len))
# AliceHere’s an example to get the longest string of the third column of a 2D array: Code: print(max(arr[:, 2], key=len))
# LeonardYou get the idea. ![]() If you want to get the longest string from the whole NumPy array, not only from a column or row or axis, first flatten it and then pass the flattened array into the Code: max()Code: key=len Recommended Tutorial: How to Flatten a NumPy Array?
|