ในการคืนค่าความยาวของสตริงอาร์เรย์ที่ชาญฉลาด ให้ใช้เมธอด numpy.char.str_len() ใน PythonNumpy เมธอดส่งคืนอาร์เรย์เอาต์พุตของจำนวนเต็ม
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
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]