파이썬에서 2 차원 배열을 정의하는 방법
다음과 같이 초기화 된 길이없이 2 차원 배열을 정의하고 싶습니다.
Matrix = [][]
하지만 작동하지 않습니다 ...
아래 코드를 시도했지만 잘못되었습니다.
Matrix = [5][5]
오류:
Traceback ...
IndexError: list index out of range
내 실수는 무엇입니까?
기술적으로 초기화되지 않은 배열을 인덱싱하려고합니다. 항목을 추가하기 전에 먼저 목록으로 외부 목록을 초기화해야합니다. 파이썬은 이것을 "목록 이해력"이라고 부릅니다.
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)]
이제 목록에 항목을 추가 할 수 있습니다.
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
매트릭스는 "y"주소 메이저입니다. 즉, "y 인덱스"가 "x 인덱스"앞에옵니다.
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
원하는대로 이름을 지정할 수 있지만, 내부 및 외부 목록 모두에 "x"를 사용하고 정사각형이 아닌 행렬을 원하는 경우 인덱싱에서 발생할 수있는 혼동을 피하기 위해이 방법을 살펴 봅니다.
정말로 행렬을 원한다면 numpy
. numpy
대부분의 행렬 연산은 2 차원 배열 유형을 사용합니다. 새 어레이를 만드는 방법에는 여러 가지가 있습니다. 가장 유용한 zeros
기능 중 하나는 함수 입니다.이 함수는 모양 매개 변수를 사용하고 값이 0으로 초기화 된 주어진 모양의 배열을 반환합니다.
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy
matrix
유형도 제공합니다 . 덜 일반적으로 사용되며 일부 사람들 은 사용하지 않는 것이 좋습니다 . 그러나 numpy
Matlab 및 다른 컨텍스트에서 오는 사람들에게 유용 합니다. 나는 우리가 행렬에 대해 이야기하고 있기 때문에 그것을 포함시킬 것이라고 생각했습니다!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
다음은 2 차원 배열과 행렬을 만드는 몇 가지 다른 방법입니다 (압축성을 위해 출력을 제거함).
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
다음은 목록 목록을 초기화하는 짧은 표기법입니다.
matrix = [[0]*5 for i in range(5)]
불행히도 이것을 다음과 같이 줄이는 것은 5*[5*[0]]
같은 목록의 5 개의 복사본으로 끝나기 때문에 실제로 작동하지 않으므로 그중 하나를 수정하면 모두 변경됩니다. 예 :
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
빈 행렬을 만들려는 경우 올바른 구문은 다음과 같습니다.
matrix = [[]]
0으로 채워진 크기 5의 행렬을 생성하려면
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
원하는 것이 일부 요소를 담는 2 차원 컨테이너 인 경우에는 대신 사전을 편리하게 사용할 수 있습니다.
Matrix = {}
그런 다음 다음을 수행 할 수 있습니다.
Matrix[1,2] = 15
print Matrix[1,2]
이것은 1,2
튜플 이기 때문에 작동 하며 사전을 색인화하는 키로 사용하고 있습니다. 결과는 벙어리 희소 행렬과 유사합니다.
osa 및 Josap Valls에서 알 수 있듯이 Matrix = collections.defaultdict(lambda:0)
누락 된 요소의 기본값이 0
.
Vatsal은이 방법이 큰 행렬에 대해 그다지 효율적이지 않을 수 있으며 코드에서 성능에 중요하지 않은 부분에서만 사용해야한다고 지적합니다.
Python에서는 목록 목록을 만듭니다. 치수를 미리 선언 할 필요는 없지만 가능합니다. 예를 들면 :
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
이제 matrix [0] [0] == 2 및 matrix [1] [0] == 3. 목록 이해 구문을 사용할 수도 있습니다. 이 예제에서는 "2 차원 목록"을 작성하기 위해 두 번 사용합니다.
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
받아 들여지는 대답은 훌륭하고 정확하지만 완전히 빈 배열을 만드는 데 사용할 수도 있다는 것을 이해하는 데 시간이 걸렸습니다.
l = [[] for _ in range(3)]
결과
[[], [], []]
목록 목록을 만들어야하며 가장 좋은 방법은 중첩 된 이해를 사용하는 것입니다.
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
귀하의 [5][5]
예에서는 내부에 정수 "5"가 포함 된 목록을 만들고 5 번째 항목에 액세스하려고하면 5 번째 항목이 없기 때문에 자연스럽게 IndexError가 발생합니다.
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
왜 그렇게 긴 코드가 Python
당신에게 묻습니까?
오랫동안 파이썬에 익숙하지 않았을 때 2D 행렬 작성에 대한 한 줄 대답을 보았고 파이썬에서 다시 2D 행렬을 사용하지 않을 것이라고 스스로에게 말했습니다. (이 한 줄은 꽤 무서웠고 파이썬이 무엇을했는지에 대한 정보를 제공하지 않았습니다. 또한 이러한 약어를 알지 못합니다.)
어쨌든, C, CPP 및 Java 배경에서 온 초보자를위한 코드입니다.
Python 애호가 및 전문가 참고 사항 : 자세한 코드를 작성했다고해서 아래로 투표하지 마십시오.
0 (1) 행렬을 선언하려면 :
numpy.zeros((x, y))
예 :
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
또는 numpy.ones ((x, y)) 예
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible. (http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix([])
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using two for loops in a list comprehension.
I read in comma separated files like this:
data=[]
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict: you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=[]
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
Try this:
rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
my_list.append(list(map(int, input().split())))
In case if you need a matrix with predefined numbers you can use the following code:
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]
l=[[0]*(L) for _ in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([]
, separated by comma) with a square bracing, just like below:
Matrix = [[], []]
Now suppose you want to append 1 to Matrix[0][0]
then you type:
Matrix[0].append(1)
Now, type Matrix and hit Enter. The output will be:
[[1], []]
참고URL : https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array-in-python
'programing tip' 카테고리의 다른 글
부호없는 정수 곱하기 오버플로를 어떻게 감지합니까? (0) | 2020.10.03 |
---|---|
Android 개발에 Java 8을 사용할 수 있습니까? (0) | 2020.10.03 |
다른 쉘 스크립트에서 쉘 스크립트를 호출하는 방법은 무엇입니까? (0) | 2020.10.02 |
값이 null 인 경우 직렬화 중에 Jackson에게 필드를 무시하도록 지시하는 방법은 무엇입니까? (0) | 2020.10.02 |
현재 파일 디렉토리의 전체 경로를 어떻게 얻습니까? (0) | 2020.10.02 |