Computer >> Máy Tính >  >> Lập trình >> C ++

Tìm độ dài của mỗi phần tử chuỗi trong mảng Numpy trong C ++

Ở đây chúng ta sẽ xem cách lấy độ dài của từng phần tử chuỗi trong Mảng Numpy. Numpy là một thư viện cho Python Numeric và nó có lớp mảng rất mạnh. Sử dụng điều này, chúng tôi có thể lưu trữ dữ liệu trong một cấu trúc giống như mảng. Để có được độ dài, chúng ta có thể làm theo hai cách tiếp cận khác nhau, chúng như sau -

Ví dụ

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)

Đầu ra

The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python']
Respective lengts: [ 5 8 6 8 11 6]

Một cách tiếp cận khác sử dụng vòng lặp

Ví dụ

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)

Đầu ra

The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python']
Respective lengts: [5, 8, 6, 8, 11, 6]