인공지능 개발자 수다(유튜브 바로가기) 자세히보기

파이썬/코딩테스트

[자료구조] 배열 (파이썬이에서는 리스트)

Suya_03 2024. 4. 20. 20:38

목차

    반응형

    시작하기 전에...

     

    코딩테스트를 준비하면서 리스트가 뭔지 아는 수준이면, 곤란하다.

    자주 사용하는 기법을 반드시 외워두고 사용하는 것이 좋겠다.

    특히 함수 사용 이후 반환된 값이 어떠한 형식인지 (list 형식인지, None 값인지, int/float/str 값인지) 반드시 알아두는 것이 좋겠다.

    특히 in-place 형식의 수정인지 알아 두는 것은 중요하다.

     

    1. 리스트 생성

    # 리스트 생성
    numbers = [1, 2, 3, 4, 5]

     

    2. 리스트에 값 추가 (append, insert, exend, +)

    • append
      • 리스트에 값 추가
      • In-place 수정 (함수사용시 리스트에 바로 추가됨)
    value = 6
    numbers.append(value)
    
    print(numbers) # [1, 2, 3, 4, 5, 6]
    • insert
      • 해당 인덱스에 값 추가
      • 기존에 있던 값들은 인덱스가 1씩 밀림
      • In-place 수정
    idx = 3
    value = 4.5
    numbers.insert(idx, value)
    
    print(numbers) # [1, 2, 3, 99, 4, 5, 6]
    • extend
      • In-place 수정
    # 리스트 생성
    fruits = ['apple', 'banana', 'cherry']
    more_fruits = ['orange', 'grape', 'melon']
    
    # 두 리스트가 연결됨
    fruits.extend(more_fruits)
    
    # 결과 출력
    print(fruits)  # 출력: ['apple', 'banana', 'cherry', 'orange', 'grape', 'melon']
    • + 연산자

     

    number1 = [1, 2, 3]
    number2 = [4, 5, 6]
    
    # 두 리스트가 연결됨
    result = number1 + number2
    print(result) # [1, 2, 3, 4, 5 ,6]

     

    3. 리스트에서 값 찾기

    • index
      • 특정 값의 인덱스를 반환
      • 찾는 값이 리스트에 없으면 오류가 발생
    fruits = ['apple', 'banana', 'cherry', 'mellon']
    
    if 'cherry' in fruites:
    	idx = fruits.index('cherry')
    	print(idx) # 2 출력
    else:
    	print('cherry' 없음)

     

    • count
      • 리스트에서 특정 값의 개수를 세어 반환
    fruits = ['apple', 'banana', 'cherry', 'mellon', 'banana', 'banana']
    
    cnt = fruits.count('banana')
    print(cnt)

     

    • 특정 값의 리스트에 있는 인덱스 전체 찾기 (동일한 값 모두, 리스트 컴프리헨션)
    fruits = ['apple', 'banana', 'cherry', 'banana', 'apple']
    indices_of_banana = [index for index, fruit in enumerate(fruits) if fruit == 'banana']
    print(indices_of_banana)  # 출력: [1, 3]

     

    • 특정 값의 리스트에 있는 인덱스 전체 찾기 1 (동일한 값 모두, Numpy)
    import numpy as np
    
    fruits = ['apple', 'banana', 'cherry', 'banana', 'apple']
    fruit_array = np.array(fruits)
    indices_of_banana = np.where(fruit_array == 'banana')[0]
    print(indices_of_banana)  # 출력: [1 3]

     

    4. 리스트에서 값 삭제

    • remove(x)
      • 리스트에서 첫번째로 나타나는 x값 삭제 (첫번째 값 하나만 삭제한다는 점!!!!)
      • 만약 x값이 없으면 에러.
      • In-place 수정
    fruits = ['apple', 'blueberry', 'banana', 'cherry', 'orange']
    fruits.remove('banana')
    print(fruits) # ['apple', 'blueberry', 'cherry', 'orange']]

     

    • pop(i)
      • defualt: 리스트의 마지막 값을 반환한다.
      • i 값을 정하면, 해당 위치의 인덱스 값을 반환한다.
      • 리스트의 마지막 값을 삭제한다.
    fruits = ['apple', 'blueberry', 'banana', 'cherry', 'orange']
    poped = fruits.pop()
    
    print(poped) # 'orange'
    print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']

     

    • del 명령어
      • 인덱스를 기반으로 값을 삭제한다.
      • 슬라이싱 방식으로 여러개의 값을 리스트에서 제거할 수도 있다.
    numbers = [10, 20, 30, 40, 50]
    del numbers[2]  # 인덱스 2의 요소 30을 제거
    print(numbers)  # 출력: [10, 20, 40, 50]
    
    del numbers[1:3]  # 인덱스 1부터 2까지의 요소들을 삭제
    print(numbers)  # 출력: [10, 50]

     

    • 특정 값 전체 제거 1 (filter 이용)
    fruits = ['apple', 'banana', 'cherry', 'banana', 'apple']
    fruits = list(filter(lambda x: x != 'banana', fruits))
    print(fruits)  # 출력: ['apple', 'cherry', 'apple']

     

    • 특정 값 전체 제거 2 (리스트 컴프리헨션 사용하기)
    fruits = ['apple', 'banana', 'cherry', 'banana', 'apple']
    fruits = [fruit for fruit in fruits if fruit != 'banana']
    print(fruits)  # 출력: ['apple', 'cherry', 'apple']

     

    5. 정렬하기

    • sort()
      • 오름차순으로 정렬
      • reverse=True 옵션을 주면, 내림차순으로 정렬함
      • In-place 수정
    fruits = ['apple', 'blueberry', 'cherry']
    fruits.sort(reverse=True)  
    print(fruits) # ['cherry', 'blueberry', 'apple']

     

    • reverse()
      • 리스트의 순서를 거꾸로 함
      • In-place 수정
    numbers = [1, 2, 3, 4, 5]
    numbers.reverse()
    print(numbers)  # 출력: [5, 4, 3, 2, 1]
    
    # 슬라이싱을 사용하여 뒤집기
    numbers = [1, 2, 3, 4, 5]
    print(numbers[::-1])  # 출력: [5, 4, 3, 2, 1]

     

    6. 슬라이싱

    슬라이싱에서 주의해야 할 내용은

    시작부분은 해당 인덱스를 포함하고

    마지막은 해당 인덱스를 포함하지 않는다는 점이다.

    numbers = [0, 1, 2, 3, 4, 5, 6]
    
    print(numbers[2:5]) # [2, 3, 4]

     

    7. 리스트 컴프리헨션

    • 기본 구조
      • expression: 리스트에 추가될 값. item을 사용하여 표현할 수 있습니다.
      • for item in iterable: 반복 가능한 객체(iterable)에서 각 요소(item)를 반복합니다.
      • if condition (선택적): 조건이 참인 경우에만 expression을 리스트에 포함합니다.
    [expression for item in iterable if condition]

     

    • 간단한 예
    # 0부터 9까지의 수 중에서 각 수의 제곱을 리스트로 생성
    squares = [x**2 for x in range(10)]
    print(squares)  # 출력: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

     

    • if문을 사용한 예
    # 0부터 9까지의 수 중 짝수의 제곱만 리스트로 생성
    even_squares = [x**2 for x in range(10) if x % 2 == 0]
    print(even_squares)  # 출력: [0, 4, 16, 36, 64]

     

    반응형