list
특징
- 1차원 배열 구조
형식) 참조변수 = [값1, 값2, ... 값n]
- 다양한 data type 저장 가능 (정수, 실수, 문자열...)
cf. 파이썬에서는 모든 자료형이 전부 객체임! ( 그래서 따로 변수에서 자료형 선언을 안 해도 되는 거!!)
- index 사용 가능, 값 수정 가능
list 생성 예제
1 2 | a = ['a', 'b', 'c'] print(a) | cs |
결과
['a', 'b', 'c']
중첩 list 만들기
1 2 3 | a = ['a', 'b', 'c'] b = [3, 0.7, true, "String", a] print(b) | cs |
결과
[3, 0.7, True, 'String', ['a', 'b', 'c']]
자료 구조, 주소값 확인하기
1 2 3 4 | a = ['a', 'b', 'c'] b = [3, 0.7, true, "String", a] print(type(a), type(b)) print(id(a), id(b)) | cs |
결과
<class 'list'> <class 'list'>90832520 91188744
list에 추가, 삽입, 삭제, 수정하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | num = ['one', 'tow', 'three', 'fore', 'five'] # 원소 추가하기 : list.append num.append('육') print(num) # 원소 삭제하기 : list.remove num.remove('five') print(num) # 원소 삽입하기 : list.insert(index, data) num.insert(0, 'zero') print(num) # 원소 수정하기 : list[index] = 수정값 num[4] = 'four' num[2] = 'two' print(num) | cs |
결과
원소 추가 : ['one', 'tow', 'three', 'fore', 'five', '육']원소 삭제 : ['one', 'tow', 'three', 'fore', '육']원소 삽입 : ['zero', 'one', 'tow', 'three', 'fore', '육']원소 수정 : ['zero', 'one', 'two', 'three', 'four', '육']
list 연결, 확장, 정렬
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | list1 = [2.5, 3.6] list2 = [5.6, 9.3] # list 연결 list3 = list1 + list2 print(list3) # list 확장 list1.append(list2) print(list1) # list 정렬 list3.sort(reverse=True) # 내림차순 print(list3) | cs |
결과
연결 : [2.5, 3.6, 5.6, 9.3]확장 : [2.5, 3.6, [5.6, 9.3]] (append를 하면 안으로 들어가는군!)정렬 : [9.3, 5.6, 3.6, 2.5]
문자열 분리
1 2 3 4 5 | word = [] # 빈 list 만들기 doc = "Somewhere over the rainbow" for w in doc.split(sep=' ') : # 문자열.split(sep='구분자') 하면 list가 됨! word.append(w) # word에 w를 삽입해라 print(word) | cs |
결과
['Somewhere', 'over', 'the', 'rainbow']
list를 활용해서 성적 처리하기
1 2 3 4 5 6 | kor = [85, 75, 90] eng = [85, 64, 90] mat = [65, 74, 64] name = ['홍길동', '이순신', '유관순'] student = [name, kor, eng, mat] print(student) | cs |
결과
[['홍길동', '이순신', '유관순'], [85, 75, 90], [85, 64, 90], [65, 74, 64]]
1 2 3 4 5 6 7 8 9 10 11 12 | hong = []; lee = []; yoo = []; for s in student : hong.append(s[0]) lee.append(s[1]) yoo.append(s[2]) classmate = [hong, lee, yoo] print('이름\t국어\t영어\t수학\t총점\t평균') print('-'*45) for c in classmate : print('{0}\t{1}\t{2}\t{3}\t{4}\t{5}' .format(c[0],c[1],c[2],c[3],c[1]+c[2]+c[3],round((c[1]+c[2]+c[3])/3,2))) | cs |
참고 : round(대상,자릿수) : 대상을 자릿수에서 반올림해라!
결과
이름 국어 영어 수학 총점 평균---------------------------------------------홍길동 85 85 65 235 78.33이순신 75 64 74 213 71.0유관순 90 90 64 244 81.33
참고 : list 내의 원소를 상대로 for 사용하기
형식
변수 = [ 실행문 for 변수 in 자료구조]
예) list 안에 있는 정수를 실수로 바꿔라!
1)
1 2 3 4 5 6 | data = [2,4,1,5] fdata = [] # 빈 리스트 만들기 for d in data : f = float(d) fdata.append(f) print(fdata) | cs |
2)
1 2 | result = [float(d) for d in data] print(result) | cs |
결과
[2.0, 4.0, 1.0, 5.0][2.0, 4.0, 1.0, 5.0] 같음!