Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

배열의 문자열 요소가 주어진 접두사로 시작하지만 테스트는 Python에서 시작하고 끝나는 부울 배열을 반환합니다.

<시간/>

배열의 문자열 요소가 접두사로 시작하는 True인 부울 배열을 반환하려면 Python Numpy에서 numpy.char.startswith() 메서드를 사용합니다. 이 메서드는 bool 배열을 출력합니다. 첫 번째 매개변수는 입력 배열입니다. 두 번째 매개변수는 접두사입니다. 선택적 시작 매개변수를 사용하여 해당 위치에서 시작하여 테스트합니다. 선택적 종료 매개변수를 사용하여 해당 위치에서 비교를 중지합니다.

단계

먼저 필요한 라이브러리를 가져옵니다 -

import numpy as np

1차원 문자열 배열 생성 -

arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])

배열 표시하기 -

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)

배열의 문자열 요소가 접두사로 시작하는 True인 부울 배열을 반환하려면 numpy.char.startswith() 메서드를 사용합니다. 이 메소드는 bool 배열을 출력합니다 -

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

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))

출력

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]