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

Đối với mỗi phần tử, trả về chỉ số thấp nhất trong chuỗi mà chuỗi con được tìm thấy trong Python

Để trả về chỉ số thấp nhất trong chuỗi nơi tìm thấy chuỗi con, hãy sử dụng phương thức numpy.char.find () trong Python Numpy. Phương thức trả về mảng đầu ra của các int. Trả về -1 nếu không tìm thấy phụ. Tham số đầu tiên là mảng đầu vào. Tham số thứ hai là chuỗi con được tìm kiếm

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', 'AmY', 'BRADley'])

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ề chỉ số thấp nhất trong chuỗi nơi tìm thấy chuỗi con, hãy sử dụng phương thức numpy.char.find () -

print("\nResult (find)...\n",np.char.find(arr, 'AT'))

Ví dụ

import numpy as np

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

# 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 lowest index in the string where substring sub is found, use the numpy.char.find() method in Python Numpy
# The method returns the output array of ints. Returns -1 if sub is not found.
# The first parameter is the input array
# The second parameter is the substring to be searched
print("\nResult (find)...\n",np.char.find(arr, 'AT'))

Đầu ra

Array...
['KATIE' 'JOHN' 'KATE' 'AmY' 'BRADley']

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (find)...
[ 1 -1 1 -1 -1]