sue
  • LIST
    2020년 08월 05일 20시 35분 58초에 업로드 된 글입니다.
    작성자: sue24
    • 순서대로 저장하는 시퀀스
    • 변경 가능한 목록
    • 입력 순서 유지(내부적으로 동적 배열로 구현)
    • 배열의 장점(연속된 공간에 요소 배치) + 연결 리스트 장점(다양한 타입을 연결해서 배치)
    • 리스트는 숫자, 문자, bool 등 다양한 타입 공존 가능

    슬라이싱

    • a[1:3] --> list a의 인덱스 1부터 인덱스 3 전까지. 즉. 인덱스 1과 2

    • a[1:4:2] --> list a의 인덱스 1부터 인덱스 4 전까지 2개씩 건너뛰면서.

      a = [1, 2, 3, 4, 5, 6]

      a[1:5:3] --> 인덱스 1부터 3칸을 건너뛰면서 출력하는데 인덱스 5 전까지 --> [1, 4]

    list 관련 기능

    • list.append(elem): O(1), 리스트 마지막에 elem 추가

    • list.pop(): O(1), 리스트 마지막 요소를 추출

      list.pop(0)처럼 숫자를 넣어 몇 번째 인덱스를 추출할 지 정할 수도 있다 이 때는 O(n). 이 작업은 큐로 하면 O(1)

    • del list[1]: O(n): 1번째 인덱스의 값을 지운다

      pop()은 값을 추출해서 반환한다는 점이 del과 다르다

      del은 리스트의 슬라이스를 지울 수도 있고 리스트 전체를 지울 수도 있다

      >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
      >>> del a[0]
      >>> a
      [1, 66.25, 333, 333, 1234.5]
      >>> del a[2:4]
      >>> a
      [1, 66.25, 1234.5]
      >>> del a[:]
      >>> a
      []
      //del can also be used to delete entire variables
      >>> del a
      // 이 뒤로 a를 호출하면 error

      del은 인덱스로 삭제하지만

      remove는 값으로 삭제한다

        fruits = ['apple', 'pear', 'strawberry', 'cherry']
      
        del fruits[1]
        print(fruits) // ['apple', 'strawberry', 'cherry']
      
        fruits.remove('strawberry')
        print(fruits) // ['apple', 'cherry']
    • list.sort(): O(nlogn): Timsort

    • min(list): O(n), 최솟값

    • max(list): O(n), 최댓값

    • list.reverse(): O(n), 뒤집기

    • len(list): O(1), list의 길이

      a = [1, 2, 3, 4]

      len(a) --> 4

      인덱스는 0~3이지만 길이는 4이다

    • list[0]: O(1), 0번째 인덱스의 값 조회

    • list.insert(3, 5): 3번 인덱스에 5 삽입

    • list.extend(iterable) == list[len(list):] = iterable: 리스트의 맨 마지막에 iterable 추가

    • list.clear(): remove all items from the list == del list[:]

    • list.index(x[,start[,end]]): 리스트에서 처음 나오는 x의 인덱스 반환. 없으면 ValueError. start와 end는 리스트이 범위를 지정해서 검색한다

    • list.count(x): list에 x가 몇 개 있는지

    • list.sort(key=None, reverse=False): 리스트에서 직접 정렬

      sorted는 새로운 리스트를 반환한다

    • list.copy() == a[:] : 리스트의 얕은 복사

        >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
        >>> fruits.count('apple')
        2
        >>> fruits.count('tangerine')
        0 !!!없어도 error가 아니군
        >>> fruits.index('banana')
        3
        >>> fruits.index('banana', 4)  # Find next banana starting a position 4
        6
        >>> fruits.reverse()
        >>> fruits
        ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
        >>> fruits.append('grape')
        >>> fruits
        ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
        >>> fruits.sort()
        >>> fruits
        ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
        >>> fruits.pop()
        'pear'

    `insert`, `remove`나 `sort`는 리스트를 변형시킬 뿐 값을 반환하지는 않는다

    모든 데이터가 정렬되거나 비교되지는 않는다

    `[None, 'hello', 10]` 는 정렬되지 않는데 integer는 string이나 None과 비교할 수 없기 때문이다

    다른 타입끼리는 비교할 수 없다

    List Comprehensions

    >>> squares = []
    >>> for x in range(10):
    ...     squares.append(x**2)
    ...
    >>> squares
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    ==

    squares = list(map(lambda x: x**2, range(10)))

    ==

    squares = [x**2 for x in range(10)]

     

    if 조건문도 삽입 가능하다

    >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    ==

    >>> combs = []
    >>> for x in [1,2,3]:
    ...     for y in [3,1,4]:
    ...         if x != y:
    ...             combs.append((x, y))
    ...
    >>> combs
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

    더 복잡한 표현도 가능하다

    >>> from math import pi
    >>> [str(round(pi, i)) for i in range(1, 6)]
    ['3.1', '3.14', '3.142', '3.1416', '3.14159']

    IndexError: 리스트 길이를 넘는 인덱스를 조회했을 때

    ! 이를 방지하려면

    try:
      print(a[9])
    except IndexError:
      print('list a에 9번 인덱스가 존재하지 않습니다.')

    '알고리즘' 카테고리의 다른 글

    연결 리스트  (0) 2020.08.24
    math 모듈1  (0) 2020.08.18
    BIg-O  (0) 2020.08.02
    Computational Thinking이 필요한 이유?  (0) 2019.10.07
    댓글