Python:배열 조건 필터 간결 구현 방식

853 단어 pythonfilter
filter 함 수 를 사용 하여 조건 판단 함 수 를 실현 하면 됩 니 다.
예 를 들 어 문자열 배열 의 민감 한 단 어 를 걸 러 내 려 면 시범 코드 는 다음 과 같 습 니 다.
#filter out some unwanted tags
def passed(item):
    try:
       return item != "techbrood" #can be more a complicated condition here
    except ValueError:
       return False
       
org_words = [["this","is"],["demo","from"],["techbrood"]]       
words = [filter(passed, item) for item in org_words]

Python 2.x 와 Python 3.x 는 filter/map 의 처리 가 호 환 되 지 않 으 므 로 Python 2.x 에서 list 를 직접 되 돌려 줍 니 다.
Python 3.x 에서 iterable 대상 을 되 돌려 줍 니 다.예 를 들 어,뒤의 숫자 는 대상 참조 주소 입 니 다.
list(words)로 변환 할 수 있 습 니 다.
참조 링크:
https://docs.python.org/3.4/library/functions.html?highlight=filter#filter

좋은 웹페이지 즐겨찾기