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

Python 목록의 첫 번째 비어 있지 않은 문자열

<시간/>

문자열 목록이 주어지면 비어 있지 않은 첫 번째 요소를 찾을 수 있습니다. 문제는 – 목록 시작 부분에 하나, 둘 또는 여러 개의 빈 문자열이 있을 수 있으며 비어 있지 않은 첫 번째 문자열을 동적으로 찾아야 한다는 것입니다.

다음으로

현재 요소가 null인 경우 다음 요소로 계속 이동하기 위해 next 함수를 적용합니다.

예시

listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using next()
res = next(sub for sub in listA if sub)
# printing result
print("The first non empty string is : \n",res)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list:
['', 'top', 'pot', 'hot', ' ', 'shot']
The first non empty string is :
top

파일러 사용

필터 조건을 사용하여 이를 달성할 수도 있습니다. 필터 조건은 null 값을 버리고 null이 아닌 첫 번째 값을 선택합니다. python2에서만 가능합니다.

예시

listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using filter()
res = filter(None, listA)[0]
# printing result
print("The first non empty string is : \n",res)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list:
['', 'top', 'pot', 'hot', ' ', 'shot']
The first non empty string is :
top