Comprehension

Published by onesixx on

리스트 컴프리헨션

  • [expression for item in iterable] 형태로, 반복문으로 리스트를 생성하는 방법

예제

  • 이 코드는 리스트 컴프리헨션을 사용하여 파일 경로를 리스트로 만듭니다.
files = [
    filename for ext in ['txt', 'xls']
    for filename in rawdatadir.glob(f'*.{ext}')
]

#### 예를 들어, 해당폴더에 아래 4개파일이 있는경우
data1.txt
data2.xlsx (이 파일은 무시됩니다)
data3.xls
data4.csv (이 파일은 무시됩니다)
#### 결과
files = [
    PosixPath('data1.txt'),
    PosixPath('data3.xls')
]
files = []
for ext in ['txt', 'xlsx', 'xls']:
    for filename in rawdatadir.glob(f'*.{ext}'):
        files.append(filename)

다른 예제

df = pd.concat([
    load_txt(file) if file.suffix == '.txt' else load_excel(file)
    for file in tqdm(files, desc='Load data from files')
])
dataframes = []
for file in tqdm(files, desc='Load data from files'):
    if file.suffix == '.txt':
        dataframes.append(load_txt(file))
    else:
        dataframes.append(load_excel(file))

df = pd.concat(dataframes)

    https://shoark7.github.io/programming/python/about-list-comprehension-python
    shoark7 github: list comprehension에서 표현식을 두 개 넘게 쓰지 말자
    """
    Comprehensions
    """
    #=== Using list (dictionary, set) comprehension
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result1 = [n for n in numbers if n % 2 == 0]
    result2 = [n for n in numbers if n % 3 == 0]
    result3 = [n * n for n in numbers]
    
    names = ['Alice', 'Bob', 'Charlie', 'David']
    name_lengths = {name: len(name) for name in names}
    
    
    
    #=== Using generator expression
    evens = (n for n in numbers if n % 2 == 0)
    multiples3 = (n for n in numbers if n % 3 == 0)
    squared_numbers = (n * n for n in numbers)
    
    for number  in evens:
        print(number)
    
    for square in squared_numbers:
        print(square)  # 1, 4, 9, 16, 25
    

    if-else expression

    #=== Using if-else expression
    condition = True
    result = 'Yes' if condition else 'No'
    
    if condition:
        result = 'Yes'
    else:
        result = 'No'
    
    #=== Using if-elif-else expression
    condition1 = True
    condition2 = False
    
    if condition1:
        result = 'Yes'
    elif condition2:
        result = 'Maybe'
    else:
        result = 'No'
    
    result = 'Yes' if condition1 else 'Maybe' if condition2 else 'No'
    
    #=== Using try-except block
    ### Handle exceptions with try-except block
    try:
        result = 1 / 0
    except ZeroDivisionError:
        result = 'Cannot divide by zero'
    
    #=== Using try-except-else block
    ### Handle exceptions with try-except-else block
    try:
        result = 1 / 1
    except ZeroDivisionError:
        result = 'Cannot divide by zero'
    else:
        result = 'Division successful'
    
    #=== Using try-except-finally block
    ### Handle exceptions with try-except-finally block
    try:
        result = 1 / 1
    except ZeroDivisionError:
        result = 'Cannot divide by zero'
    finally:
        result = 'Division finished'
    

    https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists

    nestedlist = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
    # ==flat==> [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # way1
    flat_list = [x for xs in nestedlist for x in xs]
    
    # way2
    def flatten(nestedlist):
        return [x for xs in nestedlist for x in xs]
    flat_list = flatten(nestedlist)
    
    # way3
    flat_list = []
    for xs in nestedlist:
        for x in xs:
            flat_list.append(x)        
    pp = ['aa_b','cc_d']
    
    [i.split('_') for i in pp ]
    # [['aa', 'b'], ['cc', 'd']]
    
    a = []
    b = []
    for i in pp:
        tmp = i.split('_')
        a.append(tmp[0])
        b.append(tmp[1])
    a # ['aa', 'cc']
    b # ['b', 'd']

    기본 문법

    [ ( 변수를 활용한 값 ) for ( 사용할 변수명 ) in ( iterable )]
    
    size = 10
    arr = [i * 2 for i in range(size)]
    • 변수를 활용한 값 : i * 2
    • 사용할 변수명 : i
    • iterable :  range 리스트, set, dict, tuple …

    활용

    조건문으로 필터링하기

    리스트의 크기가 iterable에 같다. 하지만 if문으로 filtering할 수 있다. .

    ## 짝수
    size = 10
    [n for n in range(1, 11) if n % 2 == 0]
    
    # [2, 4, 6, 8, 10]
    
    
    ##  2의 배수이고(AND) 3의 배수인 수만 필터링
    [n for n in range(1, 31) if n % 2 == 0 if n % 3 == 0]
    
    ## 2의 배수이거나(OR) 3의 배수인 수만 필터링
    [n for n in range(1, 16) if (n % 2)==0 or (n % 3)==0]
    


    Categories: Python Basic

    onesixx

    Blog Owner

    Subscribe
    Notify of
    guest

    0 Comments
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x