«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Recent Posts
Today
Total
관리 메뉴

짜리몽땅 매거진

[Python] 리스트 컴프리헨션, 2차원 리스트 본문

Data/Python

[Python] 리스트 컴프리헨션, 2차원 리스트

쿡국 2023. 7. 19. 17:47

리스트 컴프리헨션, 2차원 리스트

sum 을 이용한 요소들의 합 구하기
a=[1,2,3,4,5]
a
[1, 2, 3, 4, 5]
sum(a)
15
kk=0
for i in a:
    kk+=i
    
print(kk)   #kk라는 a의 요소들의 합을 나타내는 변수가 반복문 안에 입력되면 원하는 값을 출력할 수 없음. 계속해서 kk가 0으로 다시 시작함.
15
리스터 컴프리헨션
-리스트 안에 한 줄을 표현하는 것. 조금 더 간결하게 코드를 줄여서 작성하는 것

​
a=[i for i in range(10)] # = for i in range(10): print(i)
a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if문, 즉 조건식이 있는 경우

[식 for 변수 in range(횟수) if 조건식]

a=[i for i in range(20) if i%2==0]
a
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
a=[i+j for i in range(5) for j in range(10)] #이렇게 for문이 여러개인 경우 뒤쪽에서 앞쪽 순서로 진행
a
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13]
a=[i+j for i in range(2)  for j in range(3)]
a
[0, 1, 2, 1, 2, 3]
map 함수 활용하기
a=[1.1,1.5,1.8,2.7]
#만약 a 값들을 다 인트로 바꾸고 싶다
for i in range(len(a)):
    a[i] = int(a[i])
print(a)  #이렇게 하는 방법도 있지만
[1, 1, 1, 2]
b=list(map(int,a)) #이렇게 map함수를 활용하면  편리하다
b
[1, 1, 1, 2]
2차원 리스트
리스트가 2개라는 뜻
행(인덱스), 열(칼럼)의 형태
a=[[1,2],[3,4],[5,6]]
a[2][1] #리스트 안에서 값을 또 출력하고 싶을 때 a[전체 리스트 인덱스][안쪽 리스트 인덱스] 입력
6

* 추가 과제

리스트와 튜플의 차이점
튜플은 저장된 데이터가 불변이다
튜플은 순서를 바꿀 수 없다
튜플은 한 개의 함수로 여러 개의 아이템을 불러올 수 있다.
튜플은 리스트보다 메모리를 적게 사용한다.
a=(1,2,3,4,5)
for i in a:
    print(i)
1
2
3
4
5
a.append(100) #튜플은 저장된 데이터가 불변이므로 요소를 추가할 수 없다.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\2526779675.py in <module>
----> 1 a.append(100)

AttributeError: 'tuple' object has no attribute 'append'

a.extend([100,200]) #마찬가지다.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\115495566.py in <module>
----> 1 a.extend([100,200])

AttributeError: 'tuple' object has no attribute 'extend'

a[1] #인덱스는 가능
2
a.index(3)
2
a.insert(1,100) # 마찬가지로 튜플은 데이터가 불변이므로 추가 불가능
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\3189299322.py in <module>
----> 1 a.insert(1,100)

AttributeError: 'tuple' object has no attribute 'insert'

a.pop(2) #원하는 요소를 삭제할 수도 없다.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\2464652186.py in <module>
----> 1 a.pop(2)

AttributeError: 'tuple' object has no attribute 'pop'

del a #전체 삭제는 가능
a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\2167009006.py in <module>
----> 1 a

NameError: name 'a' is not defined

a=(1,2,3,4,5)
a.remove(3) #역시 불가능
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\253791346.py in <module>
----> 1 a.remove(3)

AttributeError: 'tuple' object has no attribute 'remove'

a.count(1) #요소를 추가or삭제or변경하는 것이 아니라 단순히 세는 것은 가능
1
a.sort() #튜플은 요소의 순서를 바꿀 수 없다.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\2629139315.py in <module>
----> 1 a.sort()

AttributeError: 'tuple' object has no attribute 'sort'

a.sort(reverse=True)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\1585046989.py in <module>
----> 1 a.sort(reverse=True)

AttributeError: 'tuple' object has no attribute 'sort'

a.sort(reverse=False)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\3367887115.py in <module>
----> 1 a.sort(reverse=False)

AttributeError: 'tuple' object has no attribute 'sort'

b=a.copy() #복제도 불가능
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_25520\159119658.py in <module>
----> 1 b=a.copy()

AttributeError: 'tuple' object has no attribute 'copy'

a=(1,2,3,4,5)
for i in range(len(a)):
    print(a[i])  #튜플도 반복문으로 활용 가능
1
2
3
4
5