티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Create an empty list with certain size in Python

파이썬에서 특정 크기의 빈 리스트 만들기

 문제 내용 

How do I create an empty list that can hold 10 elements?

10개의 요소를 담을 수 있는 빈 리스트를 만들고 싶습니다.

 

After that, I want to assign values in that list. For example:

그 다음, 그 리스트에 값을 할당하고 싶습니다. 예를 들어:
xs = list()
for i in range(0, 9):
   xs[i] = i

 

However, that gives IndexError: list assignment index out of range. Why?

하지만, 이렇게 하면 IndexError: list assignment index out of range가 발생합니다. 왜 그럴까요?

 


Editor's note:

에디터 주석:

 

In Python, lists do not have a set capacity, but it is not possible to assign to elements that aren't already present. Answers here show code that creates a list with 10 "dummy" elements to replace later. However, most beginners encountering this problem really just want to build a list by adding elements to it. That should be done using the .append method, although there will often be problem-specific ways to create the list more directly. Please see Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list? for details.

파이썬에서 리스트는 고정된 크기가 없습니다. 그러나 존재하지 않는 요소에 할당할 수는 없습니다. 여기에 있는 답변은 나중에 대체할 10개의 "더미" 요소로 리스트를 만드는 코드를 보여줍니다. 그러나 대부분의 초보자는 이 문제를 만날 때 리스트를 만드는 것이 아니라 요소를 추가해 나가는 것이 실제로 필요합니다. .append 메서드를 사용하여 이를 수행해야 하며, 문제별로 더 직접적으로 리스트를 만드는 방법이 있을 수 있습니다. 자세한 내용은 Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list?를 참조하십시오.

 

 

 

 높은 점수를 받은 Solution 

You cannot assign to a list like xs[i] = value, unless the list already is initialized with at least i+1 elements. Instead, use xs.append(value) to add elements to the end of the list. (Though you could use the assignment notation if you were using a dictionary instead of a list.)

이미 초기화된 i+1개 이상의 요소를 가진 리스트가 있지 않은 한 xs[i] = value와 같이 리스트에 할당할 수 없습니다. 대신, xs.append(value)를 사용하여 요소를 리스트의 끝에 추가하세요. (하지만 딕셔너리 대신 리스트를 사용하는 경우 할당 표기법을 사용할 수 있습니다.)

 

Creating an empty list:

빈 리스트 생성:
>>> xs = [None] * 10
>>> xs
[None, None, None, None, None, None, None, None, None, None]

 

Assigning a value to an existing element of the above list:

위의 리스트의 기존 요소에 값을 할당하는 방법:
>>> xs[1] = 5
>>> xs
[None, 5, None, None, None, None, None, None, None, None]

 

Keep in mind that something like xs[15] = 5 would still fail, as our list has only 10 elements.

리스트에 최소한 10개의 요소가 있지 않으면 xs[15] = 5와 같은 것은 여전히 실패할 것입니다.

 

range(x) creates a list from [0, 1, 2, ... x-1]

range(x)는 [0, 1, 2, ..., x-1]에서 리스트를 만듭니다.
# 2.X only. Use list(range(10)) in 3.X.
>>> xs = range(10)
>>> xs
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Using a function to create a list:

함수를 사용하여 리스트를 만드는 방법:
>>> def display():
...     xs = []
...     for i in range(9): # This is just to tell you how to create a list.
...         xs.append(i)
...     return xs
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

 

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

리스트 내포(range를 사용하는 경우 모든 것을 이렇게 할 필요는 없으며, 단순히 range(0,9)를 반환할 수 있습니다.):
>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

 

 

 가장 최근 달린 Solution 

Another option is to use numpy for fixed size arrays (of pointers):

포인터의 고정 크기 배열을 위해 numpy를 사용할 수 있는 또 다른 옵션은 다음과 같습니다:

 

> pip install numpy

import numpy as np


a = np.empty(10, dtype=np.object)
a[1] = 2
a[5] = "john"
a[3] = []

 

If you just want numbers, you can do with numpy:

숫자만 필요한 경우 numpy를 사용하여 다음과 같이 할 수 있습니다:
a = np.arange(10)

 

 

출처 : https://stackoverflow.com/questions/10712002/create-an-empty-list-with-certain-size-in-python

반응형
댓글
공지사항
최근에 올라온 글