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

Trả về một mảng boolean trong đó phần tử chuỗi trong mảng bắt đầu bằng một tiền tố đã cho nhưng kiểm tra bắt đầu và kết thúc bằng Python

Để trả về một mảng boolean là True trong đó phần tử chuỗi trong mảng bắt đầu bằng tiền tố, hãy sử dụng phương thức numpy.char.startswith () trong Python Numpy. Phương thức này xuất ra một mảng bools. Tham số đầu tiên là mảng đầu vào. Tham số thứ hai là tiền tố. Với tham số bắt đầu tùy chọn, kiểm tra bắt đầu tại vị trí đó. Với tham số kết thúc tùy chọn, dừng so sánh ở vị trí đó.

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(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])

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ề một mảng boolean là True trong đó phần tử chuỗi trong mảng bắt đầu bằng tiền tố, hãy sử dụng phương thức numpy.char.startswith (). Phương thức này xuất ra một mảng bools -

print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2))

Ví dụ

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])

# 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 a boolean array which is True where the string element in array begins with prefix, use the numpy.char.startswith() method in Python Numpy
# The method outputs an array of bools.
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2))

Đầu ra

Array...
['KATIE' 'JOHN' 'KATE' 'KmY' 'BRAD']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (startswith)...
[ True False True True False]