list 갯수 제한 질문
조회수 2482회
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 답변
-
>>> 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]
댓글 입력