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

Trả về độ dài của một phần tử mảng chuỗi trong Python

Để trả về độ dài của một phần tử mảng chuỗi, hãy sử dụng phương thức numpy.char.str_len () trong PythonNumpy. Phương thức trả về một mảng đầu ra gồm các số nguyên.

Các bước

Đầu tiên, hãy nhập thư viện được yêu cầu -

import numpy as np

Tạo mảng chuỗi một chiều -

arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])

Hiển thị mảng của chúng tôi -

print("Array...\n",arr)

Nhận loại dữ liệu -

print("\nArray datatype...\n",arr.dtype)

Nhận các kích thước của Mảng -

print("\nArray Dimensions...\n",arr.ndim)

Nhận hình dạng của Mảng -

print("\nOur Array Shape...\n",arr.shape)

Nhận số phần tử của Mảng -

print("\nNumber of elements in the Array...\n",arr.size)

Để trả về độ dài của một phần tử mảng chuỗi, hãy sử dụng phương thức numpy.char.str_len () -

print("\nResult (length element-wise)...\n",np.char.str_len(arr))

Ví dụ

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))

Đầu ra

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]