list 갯수 제한 질문

조회수 2478회
N=int(input())

N_list=list(map(int,input().split()))

print(min(N_list),max(N_list))

N_list의 개수를 제한하고싶습니다. 예를 들어 N의 정수가 5이면 N_list에 들어갈수있는 정수들은 5개 까지만 들어갈 수 있도록 해보고 싶은데...

if N_list[]<N:

if문 등 생각해본 방법대로 해봤는데 index error가 나옵니다. 어떻게 해결해야할지 도움부탁드립니다..ㅜ

2 답변

  • 좋아요

    0

    싫어요
    채택 취소하기
    >>> N = int(input())
    5
    >>> N_list = list(map(int, input().split()[:N]))
    1 2 3 4 5 6 7 8 9
    >>> N_list
    [1, 2, 3, 4, 5]
    
  • collections 모듈에 deque 을 사용하거나 UserList 를 상속해서 사용하는 방법이 편합니다.

    from collections import deque, UserList
    q = deque([], maxlen=5)
    q.append(1) # 최대 5개만 저장 가능합니다.
    
    class MyList(UserList):
        def __init__(self, n):
            self.n = n
            self.data = [None] * n
        def append(self, n):
            raise Exception(f"exceed the limit.[{self.n}]")
    
    my_list = MyList(5)
    my_list
    Out[45]: [None, None, None, None, None]
    
    my_list.append(6)
    ---------------------------------------------------------------------------
    Exception                                 Traceback (most recent call last)
    <ipython-input-47-c44ca8f1f6a6> in <module>
    ----> 1 my_list.append(6)
    
    <ipython-input-43-b212c25e065a> in append(self, n)
          4         self.data = [None] * n
          5     def append(self, n):
    ----> 6         raise Exception(f"exceed the limit.[{self.n}]")
          7
    
    Exception: exceed the limit.[5]
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)