[PY4E] 파이썬 리스트; append() sort() split() range()
1. 프로그래밍 = 알고리즘 + 자료구조
- 알고리즘 : 문제를 해결 하기 위한 규칙 또는 단계
- 자료구조 : 컴퓨터내에서 자료를 구조화&구성하는 특별한 방법
2. 컬렉션
- 일반 변수 : 새 값을 대입하면 덮어씌워짐
- 리스트 = 컬렉션의 일종
- 하나의 '변수'에 많은 값을 넣을 수 있음
3. 리스트 List (시퀀스 자료형)
- [ ] 대괄호로 둘러싸여 있음
- 반점( , )으로 구분
- 파이썬의 어떤 객체도 원소로 넣을 수 있음
- 다른 list도 넣을 수 있음
- 빈 list도 생성 가능
- 문자열 내용 "변경 불가" / 리스트 내용 "변경 가능"
> 인덱스indexing 사용 : 값에 접근하기 위해 주소값 사용, 0부터 시작
- len() : 리스트의 원소 갯수 반환
- range() : 0부터 매개 변수로 넣은 값보다 1 작은 범위의 수까지 숫자 리스트 반환
>>> mix = ['Joseph', ['yellow','blue'], 26, 96]
>>> emptyList = []
>>> print(mix[0]) #indexing
Joseph
>>> print(emptyList)
[]
>>> mix[2] = 14
>>> print(mix)
['Joseph', ['yellow', 'blue'], 14, 96]
>>> print(len(mix))
4
>>> for i in range(3):
... print(i)
0
1
2
- list & 유한루프
: 파이썬은 복수 단수 신경x / 어떤 변수를 쓰더라도 상관없다는 점 명심
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print('Happy New Year:', friend)
for i in range(len(friends)) :
friend = friends[i]
print('Happy New Year:', friend)
z = ['Joseph', 'Glenn', 'Sally']
for x in z:
print('Happy New Year:', x)
# 둘 다 동일한 코드!!
- 리스트 자료구조 : https://docs.python.org/3/tutorial/datastructures.html
5. Data Structures — Python 3.10.5 documentation
5. Data Structures This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. 5.1. More on Lists The list data type has some more methods. Here are all of the methods of list objects: list.append(x)
docs.python.org
4. 리스트 병합&자르기
- '+' 연산자를 사용하여 새로운 리스트 생성 가능
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
- 슬라이싱 slicing [시작 인덱스 : 마지막 인덱스 : 증가값] :(콜론)을 사용하여 자름
- 마지막 인덱스 -1까지만 포함(문자열과 동일)
- 리버스 인덱스 reverse index : 인덱스를 마지막 값부터 시작(음수)
- 인덱스 범위를 넘어가는 슬라이싱 : 자동으로 시작 인덱스와 마지막 인덱스로 지정
>>> print(c[1:3])
[2, 3]
>>> print(c[-5::2])
[2, 4, 6]
#-5 -3 -1
>>>c[-50:50]
[1, 2, 3, 4, 5, 6]
5. 리스트 메소드
- dir() : 리스트 메소드에 대해 보여줌
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
- 리스트 원소 추가 append()
: 빈 리스트를 만들고 append 매소드로 원소 추가
: 순서 유지, 새 원소는 끝에 더해짐
>>> stuff = list()
>>> stuff.append('book')
>>> stuff.append(99)
>>> print(stuff)
['book', 99]
>>> stuff.append('cookie')
>>> print(stuff)
['book', 99, 'cookie']
- 리스트에 새로운 리스트 추가 extend()
>>> stuff = ['book', 99]
>>> stuff.extend(['cookie', 'tissues'])
>>> print(stuff)
['book', 99, 'cookie', 'tissues']
- n번째 주소에 원소 추가 insert()
: 0번째 주소에 'notebook'이라는 원소 추가됨 > 뒤쪽의 인덱스는 하나씩 밀림
>>> stuff = ['book', 99, 'cookie', 'tissues']
>>> stuff.insert(0, 'notebook')
>>> print(stuff)
['notebook', 'book', 99, 'cookie', 'tissues']
- 리스트 원소 탐색 in / not in
: 리스트 안에 특정 원소가 있는지 check
: 논리연산 - True or Faalse 반환
>>> stuff = ['book', 99, 'cookie']
>>> print(9 in stuff)
False
>>> print(90 not in stuff)
True
- 리스트 삭제 remove() / del
remove() : 원소의 이름을 입력해서 삭제
del : 리스트의 주소를 입력해서 삭제
>>> stuff = ['notebook', 'book', 99, 'cookie', 'tissues']
>>> stuff.remove('notebook')
>>> print(stuff)
['book', 99, 'cookie', 'tissues']
>>> del stuff[1]
>>> print(stuff)
['book', 'cookie', 'tissues']
- 리스트 정렬 sort()
: 리스트 그 자체를 순서대로 정렬 가능(문자열은 불가)
: 숫자와 문자열 동시에는 불가
>>> stuff = ['book', 99, 'cookie']
>>> stuff.sort()
>>> print(stuff)
TypeError: '<' not supported between instances of 'int' and 'str'
: sort() & sort(reverse=False) 오름차순 정렬 #디폴트값
: sort(reverse=True) 내림차순 정렬
>>> a = ['cookie','ad', 'book']
>>> a.sort()
>>> print(a)
['ad', 'book', 'cookie']
>>> b = [1,2,56,3,6]
>>> b.sort(reverse=False) #디폴트 값
>>> print(b)
[1, 2, 3, 6, 56]
>>> c = ['Cookie', 'Ad', 'Book']
>>> c.sort(reverse=True) #내림차순 정렬
>>> print(c)
['Cookie', 'Book', 'Ad']
- 여러 내장 함수
max() 최댓값 계산 / min() 최솟값 계산 / sum() 합계 계산
#type1 기존의 풀어서 계산하는 루프
total = 0
count = 0
while True :
inp = input('Enter a number: ')
if inp == 'done' : break ## 끝에 붙여서 멈추게 함
value = float(inp)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
#type2 리스트 사용하는 루프
numlist = list()
while True :
inp = input('Enter a number: ')
if inp == 'done' : break ## 끝에 붙여서 멈추게 함
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
>> 둘다 결과는 동일. 단지, #type2가 메모리 더 많이 사용
>> 둘다 이해하고 필요에 따라 사용
- 나누기 split()
: 문자열에서 구획 문자을 기준으로 여러조각으로 나누어 리스트로 반환
: 마치 문자열을 단어 기준으로 나누어 그 단어를 반환하는 것
: 여러 칸의 공백도 하나의 구획 문자로 여겨짐
: 어떤 구획문자를 사용할 지 정할 수 있음
>>> line = 'A lot of spaces'
>>> etc = line.split()
>>> print(etc)
['A', 'lot', 'of', 'spaces']
>>> line = 'first;second;third'
>>> thing = line.split(';')
>>> print(thing)
['first', 'second', 'third']
>>> print(len(thing))
3
- 이중으로 나누는 패턴
line = "From stephen.marquard@ect.ac.za Sat Jan 5 09:14:16 2008"
words = line.split()
print(words[1])
# stephen.marquard@ect.ac.za
email = words[1]
address = email.split("@")
print(address)
# ['stephen.marquard', 'ect.ac.za']
print(address[1])
# ect.ac.za
> 1차 : 공백으로 구분
> 2차 : @로 구분
파이썬 리스트 추가 - 패킹, 언패킹, 행렬 > https://dailystudy.tistory.com/39
[AI 기초 다지기] 파이썬 리스트 - 패킹, 언패킹, 행렬
파이썬 리스트; append() sort() split() > https://dailystudy.tistory.com/29 - 패킹: 한 변수에 여러 개의 데이터를 넣는 것 - 언패킹 : 한 변수의 데이터를 각각의 변수로 반환 >>> t = [1, 2, 3] ## 패킹 >>>..
dailystudy.tistory.com
* 내용참고&출처 : 태그의 수업을 복습 목적으로 정리한 내용입니다.