按元素返回 Python 中字串陣列的長度
若想按元素返回字串陣列的長度,請在 Python Numpy 中使用 numpy.char.str_len() 方法。該方法將返回一個整數輸出陣列。
步驟
首先,匯入所需的庫 −
import numpy as np
建立一個一維字串陣列 −
arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])
顯示此陣列 −
print("Array...\n",arr)獲取資料型別 −
print("\nArray datatype...\n",arr.dtype)
獲取陣列的維度 −
print("\nArray Dimensions...\n",arr.ndim)獲取陣列的形狀 −
print("\nOur Array Shape...\n",arr.shape)獲取陣列中元素的數目 −
print("\nNumber of elements in the Array...\n",arr.size)若想按元素返回字串陣列的長度,請使用 numpy.char.str_len() 方法 −
print("\nResult (length element-wise)...\n",np.char.str_len(arr))
示例
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])
# Displaying our array
print("Array...\n",arr)
# Get the datatype
print("\nArray datatype...\n",arr.dtype)
# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)
# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)
# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)
# To return the length of a string array element-wise, use the numpy.char.str_len() method in Python Numpy
# The method returns an output array of integers.
print("\nResult (length element-wise)...\n",np.char.str_len(arr))輸出
Array... ['Amy' 'Scarlett' 'Katie' 'Brad' 'Tom'] Array datatype... <U8 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (length element-wise)... [3 8 5 4 3]
Advertisement
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP