접두어 발생 여부에 따라 문자열을 분할해야 하는 경우 두 개의 빈 목록이 정의되고 접두어 값이 정의됩니다. 'append' 메서드와 함께 간단한 반복이 사용됩니다.
예시
아래는 동일한 데모입니다 -
from itertools import zip_longest
my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']
print("The list is : " )
print(my_list)
my_prefix = "python"
print("The prefix is :")
print(my_prefix)
my_result, my_temp_val = [], []
for x, y in zip_longest(my_list, my_list[1:]):
my_temp_val.append(x)
if y and y.startswith(my_prefix):
my_result.append(my_temp_val)
my_temp_val = []
my_result.append(my_temp_val)
print("The resultant is : " )
print(my_result)
print("The list after sorting is : ")
my_result.sort()
print(my_result) 출력
The list is : ['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne'] The prefix is : python The resultant is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']] The list after sorting is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]
설명
-
필요한 패키지를 환경으로 가져옵니다.
-
문자열 목록이 정의되고 콘솔에 표시됩니다.
-
접두사 값이 정의되어 콘솔에 표시됩니다.
-
두 개의 빈 목록이 정의됩니다.
-
'zip_longest' 메소드는 반복에서 첫 번째 값을 생략하여 동일한 목록과 함께 목록을 결합하는 데 사용됩니다.
-
요소는 빈 목록 중 하나에 추가됩니다.
-
이 목록은 콘솔에 출력으로 표시됩니다.
-
이 목록은 다시 정렬되어 콘솔에 표시됩니다.