Xem cách lấy độ dài từng phần tử chuỗi trong mảng NumPy. NumPy là thư viện Python cho tính toán số học, có lớp mảng mạnh mẽ. Có hai cách lấy độ dài:
Cách 1: Sử dụng np.vectorize(len)
import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_check = np.vectorize(len)
len_arr = len_check(str_arr)
print('Respective lengts: ', len_arr)
Kết quả
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [ 5 8 6 8 11 6]
Cách 2: Sử dụng list comprehension
import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_arr = [len(i) for i in str_arr]
print('Respective lengts: ', len_arr)
Kết quả
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [5, 8, 6, 8, 11, 6]