[Python] 파일 & 데이터 구조 다루기

NAEMAMDAEROG·2021년 12월 1일
0

파일 다루기

파일 열기/닫기

file = open('data.txt')  # 기본값 : 읽기(read) 모드
content = file.read()
file.close()  # 무조건 close() 해줘야 됨

파일 자동으로 닫기

with open('data.txt') as file:
	content = file.read()  # 들여쓰기가 끝나면 file이 자동으로 닫힌다.
# file.close() - 필요 없음

줄 단위로 읽기

contents = []
with open('data.txt') as file:
	for line in file:
    	contents.append(line)

파일의 모드

# 쓰기(write) 모드
with open('data.txt', 'w') as file:
	file.write('Hello')

데이터 구조 다루기

튜플(tuple)

apple = ('사과', 'apple', 'pomme')
  • tuple vs list
    • 공통점 : 순서가 있는 원소들의 집합
    • 차이점 : 각 원소의 값을 수정할 수 없음, 원소의 개수를 바꿀 수 없음
    • 인덱스로 값을 가지로 올 수는 있으나, 인덱스로 값을 할당하는 건 불가능.

데이터 정렬

numbers = [-1, 3, -4, 5, 6, 100]
sort_by_abs = sorted(numbers, key=abs)
# key가 abs이므로 abs()에 넣었을 때 나오는 결과값을 기준으로 정렬
# [-1, 3, -4, 5, 6, 100]
  • sort : list.sort()로 원본 리스트를 정렬 (list의 method)
  • sorted : sorted(list)로 정렬된 리스트를 반환. 원본 리스트는 변하지 않는다. 기본값은 오름차순 (python의 내장함수)
def reverse(word):
	return str(reversed(word))
    
fruits = ['cherry', 'apple', 'banana']
sort_by_last = sorted(fruits, key=reverse)
ex) reverse('apple') = 'elppa'
# 문자열을 넣었을 때 거꾸로 나온 값을 기준으로 정렬한다.
# ['banana', 'apple', 'cherry']

Counter

  • 편리하고 빠르게 개수를 세도록 도와준다.
import collections import Counter

cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']
	cnt[word] += 1
cnt # Counter({'blue': 3, 'red': 2, 'green': 1})

Counter('hello world') 
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

출처: 엘리스 AI트랙 3기 11주차 수업

profile
Blockchain & Programming 공부 기록

0개의 댓글