Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สำหรับแต่ละองค์ประกอบส่งคืนดัชนีสูงสุดในสตริงที่พบสตริงย่อยในช่วงในPython


หากต้องการคืนค่าดัชนีสูงสุดในสตริงที่พบสตริงย่อย ให้ใช้เมธอด numpy.char.rfind() ใน Python Numpy เมธอดส่งคืนอาร์เรย์เอาต์พุตของ int ส่งกลับ -1 หากไม่พบย่อย

พารามิเตอร์แรกคืออาร์เรย์อินพุต พารามิเตอร์ที่สองคือสตริงย่อยที่จะค้นหา พารามิเตอร์ที่สามและสี่เป็นอาร์กิวเมนต์ที่ไม่บังคับ โดยที่จุดเริ่มต้นและจุดสิ้นสุดจะถูกตีความว่าเป็นสัญกรณ์สไลซ์

ขั้นตอน

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import numpy as np

สร้างอาร์เรย์หนึ่งมิติของสตริง -

arr = np.array(['KATIE', 'JOHN', 'AmY', 'BRATleuATp'])

กำลังแสดงอาร์เรย์ของเรา -

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.rfind() -

print("\nResult (find)...\n",np.char.rfind(arr, 'AT', start = 4, end = 9))

ตัวอย่าง

import numpy as np

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

# 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 highest index in the string where substring sub is found, use the numpy.char.rfind() method in Python Numpy

print("\nResult (find)...\n",np.char.rfind(arr, 'AT', start = 4, end = 9))

ผลลัพธ์

Array...
['KATIE' 'JOHN' 'AmY' 'BRATleuATp']

Array datatype...
<U10

Array Dimensions...
1

Our Array Shape...
(4,)

Number of elements in the Array...
4

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