2738 (완)

chi·2023년 3월 29일

백준

목록 보기
3/20
post-thumbnail
import sys
input=sys.stdin.readline
a= list(map(int,input().split())) # n m matrix
b=[]; c=[]; e=[]
for i in range(a[0]): #n rows
    b+=list(map(int,input().split()))
for i in range(a[0]):
    c+=list(map(int,input().split()))
for i in range(a[0]):
    e[i]+=(b[i][n]+c[i][n] for n in range(a[1]))
print(e)

>>>Traceback (most recent call last):
  File "c:\Users\YoonSeo\Desktop\백준\testin3.py", line 10, in <module>
    e[i]+=(b[i][n]+c[i][n] for n in range(a[1]))
IndexError: list index out of range

e[i]+=(b[i][n]+c[i][n] for n in range(a[1]))
이거 하면 대체 어떻게 나오는

import sys
input=sys.stdin.readline
a= list(map(int,input().split())) # n m matrix
b=[]; c=[]; e=[]
for i in range(a[0]): #n rows
    b+=list(map(int,input().split()))
for i in range(a[0]):
    c+=list(map(int,input().split()))
for i in range(a[0]):
    for n in range(a[1]):
        e[i][n]+=(b[i][n]+c[i][n])
print(e)

list index out of range 오류가 난 게 e 리스트에 아무것도 없는데 인덱스 써서 그럼

import sys
input=sys.stdin.readline
a= list(map(int,input().split())) # n m matrix
b=([0]*a[1])*a[0]; c=([0]*a[1])*a[0]; e=([0]*a[1])*a[0]
for i in range(a[0]): #n rows
    b+=list(map(int,input().split()))
for i in range(a[0]):
    c+=list(map(int,input().split()))
for i in range(a[0]):
    for n in range(a[1]):
        e.append(b[i][n]+c[i][n]) #리스트??를 더하는 게 아니라 요소를 더하는.
print(e)
>>>Traceback (most recent call last):
  File "c:\Users\YoonSeo\Desktop\백준\testin3.py", line 11, in <module>
    e.append(b[i][n]+c[i][n])
TypeError: 'int' object is not subscriptable

'int' object is not subscriptable 오류
정수를 인덱싱 하려고 해서.
이거 하려면 이차원배열을 초기화해야 됨

([0]*m)*n
>>> ([0]*6)*3
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

이차원배열 초기화를 모두 0으로 하는 건 안 되나?

이차원배열

이차원배열 초기화 어떻게 함?

b=([0]*a[1])*a[0]; c=([0]*a[1])*a[0]; e=([0]*a[1])*a[0]

이렇게 하는 거 아님?
Q 아님 array라서 걍 사이즈 고정?

아니 왜 이차원배열로 저장이 안 됨?
배열 더하기를 해놨으니까.
[1,1]+[1,1] 은 [1,1],[1,1] 이 아니라 [1,1,1,1]임.


고치기 전은 b랑 c 빈 배열에 더해서 리스트 속의 리스트가 생긴 것도 아니고 그냥 그 자체가 됐네

완성

import sys
input=sys.stdin.readline
a= list(map(int,input().split())) # n m matrix
b=[]; c=[]; e=[]
for i in range(a[0]): #n rows
    b.append(list(map(int,input().split())))
for i in range(a[0]):
    c.append(list(map(int,input().split())))
for i in range(a[0]):
    e.append([b[i][j]+c[i][j] for j in range(a[1])])
print(e)

이차원배열 공백없이 출력

import sys
input=sys.stdin.readline
a= list(map(int,input().split())) # n m matrix
b=[]; c=[]; e=[]
for i in range(a[0]): #n rows
    b.append(list(map(int,input().split())))
for i in range(a[0]):
    c.append(list(map(int,input().split())))
for i in range(a[0]):
    e.append([b[i][j]+c[i][j] for j in range(a[1])])
    print(' '.join(map(str,e[i])))
    

리스트를 꼭 문자열로 변환시키고 해야 typeError가 안 난다
이차원배열의 경우 1행도 리스트고 2행도 리스트,,,,니까 지금 모양이
[[a,b],[c,d]]
전체 리스트를 대상으로 map(str,e) 하면 '[a,b],[c,d]' 이렇게 되니까 꼭 한 행씩 map(str,e[i]) 해서 'a,b' 와 'c,d'로 만들어놓고 시작


시간도 짧게걸렸다 제한시간이 1초였던 거 보면 원래 이차원배열에 접근할 때는 이중for문이 불가피한가봄??? 모름

0개의 댓글