ที่นี่เราจะเห็นวิธีหาความยาวของแต่ละสมาชิกสตริงในอาร์เรย์ Numpy Numpy เป็นไลบรารีสำหรับ Numeric Python และมีคลาสอาร์เรย์ที่ทรงพลัง ด้วยนี้เราสามารถเก็บข้อมูลในโครงสร้างแบบอาร์เรย์ได้ เพื่อหาความยาวเราสามารถทำตามสองวิธีที่แตกต่างกัน ดังนี้ −
ตัวอย่าง
import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_check = np.vectorize(len)
len_arr = len_check(str_arr)
print('Respective lengts: ', len_arr)
ผลลัพธ์
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [ 5 8 6 8 11 6]
อีกวิธีหนึ่งใช้ลูป
ตัวอย่าง
import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_arr = [len(i) for i in str_arr]
print('Respective lengts: ', len_arr)
ผลลัพธ์
The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python'] Respective lengts: [5, 8, 6, 8, 11, 6]