Python

[Python/level 0] 문자열 잘라서 정렬하기 - 181866, filter(function, iterable)

Se On 2024. 8. 31. 07:39

문제 설명

문자열 myString이 주어집니다. "x"를 기준으로 해당 문자열을 잘라내 배열을 만든 후 사전순으로 정렬한 배열을 return 하는 solution 함수를 완성해 주세요.

단, 빈 문자열은 반환할 배열에 넣지 않습니다.

 

filter(function, iterable)

Parameter Description
function A Function to be run for each item in the iterable
iterable The iterable to be filtered
  • The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not.
    filter() 함수는 함수를 통해 항목을 필터링 → 항목이 허용되는지 여부를 테스트하여 iterator를 반환합니다.
  • function 부분은 람다 함수를 사용하여 더욱 간단한 코드를 만들 수 있습니다.
    • filter(lambda u: u["gender"] == "F, users)

 

filter(function, iterable)에서 사용할 수 있는 함수

함수 종류 설명 예시
None iterator 내에서 True 요소만(False로 평가되지 않는) 반환됩니다. data = [0, 1, False, True, "", "Python", None[], [1, 2]]
result = list(filter(None, data))
print(result)  # [1, True, 'Python', [1, 2]]
lambda 함수 조건식을 간단히 정의할 수 있습니다. numbers = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, numbers))
print(result)  # [2, 4, 6]
custom 함수 사용자가 정의한 함수를 사용하여 조건에 맞는 요소를 필터링할 수 있습니다. def is_positive(n):
    return n > 0

numbers = [-1, 0, 2, -3, 5, -8]
result = list(filter(is_positive, numbers))
print(result)  # [2, 5]
str.isdigit 문자열이 숫자로만 이루어져 있는지 확인합니다. data = ["123", "abc", "456", "def"]
result = list(filter(str.isdigit, data))
print(result)  # ['123', '456']
str.isalpha 문자열이 알파벳 문자로만 이루어져 있는지 확인합니다. data = ["123", "abc", "456", "def"]
result = list(filter(str.isalpha, data))
print(result)  # ['abc', 'def']
str.islower / str.isupper 소문자 / 대문자로만 이루어진 문자열을 필터링합니다. data = ["ABC", "abc", "DEF", "ghi"]
lower_result = list(filter(str.islower, data))
upper_result = list(filter(str.isupper, data))

print(lower_result)  # ['abc', 'ghi']
print(upper_result)  # ['ABC', 'DEF']
str.startswith / str.endswith 특정 문자열로 시작 / 끝나는 요소를 필터링할 때 사용합니다. data = ["apple", "banana", "cherry", "date"]
starts_with_b = list(filter(lambda x: x.startswith('b'), data))
ends_with_e = list(filter(lambda x: x.endswith('e'), data))

print(starts_with_b)  # ['banana']
print(ends_with_e)    # ['apple', 'date']
  • filter() 함수는 리스트 컴프리헨션으로 대체할 수 있습니다.

 

 

⚠️주의사항⚠️

  • filter() 함수는 filter 타입으로 결과를 리턴합니다.
    • filter(lambda u: u["email"].endswith("@gmail.com"), users)
      => <filter object at 0x11132f7c0>
  • filter() 함수의 결과 값을 리스트로 변환하는 가장 쉬운 방법은 list() 내장 함수를 사용하는 것입니다.
    • list(filter(lambda u: u["email"].endswith("@gmail.com"), users))
      => [{'mail': 'gr@gmail.com', }, ... ]
  • 참고자료

 

 

code - 1차

def solution(myString):
    splitString = myString.split('x')
    # 빈 문자열 = 거짓
    result = [s for s in splitString if s]
    result.sort()
    return result

 

 

code - 2차

def solution(myString):
    # sample_list = list(filter(None, sample_list))
    return sorted(list(filter(None, myString.split("x"))))
  • filter 함수를 사용하여 코드 리팩토링을 진행하였습니다.

 

반응형