在C ++中找到Numpy数组中每个字符串元素的长度
在这里,我们将看到如何获取Numpy数组中每个字符串元素的长度。Numpy是适用于NumericPython的库,它具有非常强大的数组类。使用此方法,我们可以将数据存储在类似结构的数组中。为了得到长度,我们可以采用两种不同的方法,如下所示-
示例
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)
输出结果
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [ 5 8 6 8 11 6]
使用循环的另一种方法
示例
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)
输出结果
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [5, 8, 6, 8, 11, 6]