Data Science/python & pytorch
[python] Basics of python
sunnyshiny
2023. 12. 29. 18:59
728x90
Python 기본 입출력¶
- sep : 여러 변수를 출력할 때 값 값을 구분하기위한 문자(seperate)
- end : 마지막 문자열을 출력하고 출력할 문자
data1= 10 data2 = 20 data3 = 30 print(data1, data2, data3) print(data1, data2, data3, sep=',') print(data1, data2, data3, end='[END]')
In [6]:
score = 60
print('Score: %i' %score)
print(f'Score: {score}')
print('Score :{}'.format(score))
Score: 60 Score: 60 Score :60
In [7]:
data = input()
# input 을 하면 입력 처리를 위한 함수가 실행되고 입력된 결과를 print로 출력
print(data)
hello
Escape문자¶
- \": 큰따옴표를 출력한다.
- \': 작은따옴표를 출력한다.
- \n: 줄바꿈(new line) 문자를 출력한다.
- \t: 탭(tab) 문자를 출력한다.
- \: 백슬래시(backslash) 문자를 출력한다.
In [9]:
print('큰 따옴표: \"Hello.\"')
print('작은 따옴표: \'Hello\'')
print('줄바꿈: Hello. \n Hello!!')
print('탭하여 출력: Hello. \t Hello!!')
print('백슬래시: Hello. Hello!!\\')
큰 따옴표: "Hello." 작은 따옴표: 'Hello' 줄바꿈: Hello. Hello!! 탭하여 출력: Hello. Hello!! 백슬래시: Hello. Hello!!\
리스트 매서드¶
- insert(삽입할 인텍스, 삽입할 원소)
- append(삽입할 원소)
- remove(삭제할 원소)
- sort(리스트 원소 정렬): reverse=True 내림차순 정렬
In [10]:
arr = [1, 3, 4]
print('원래 리스트: ', arr)
arr.insert(1, 2) # 인덱스 1의 위치에 원소 2를 삽입
print('insert:', arr)
arr.append(5) # 리스트의 마지막에 5를 삽입
print('append:', arr)
arr.remove(2)
print('remove:', arr)
arr.sort()
print('오름차순: ',arr)
arr.sort(reverse=True)
print('내림차순: ',arr)
원래 리스트: [1, 3, 4] insert: [1, 2, 3, 4] append: [1, 2, 3, 4, 5] remove: [1, 3, 4, 5] 오름차순: [1, 3, 4, 5] 내림차순: [5, 4, 3, 1]
Dictionary¶
- key, value형태로 저장하고 기록
In [11]:
dict = {}
keys = ['name', 'address', 'age']
values = ['kim', 'seoul', '10']
for i in range(len(keys)):
dict[keys[i]]= values[i]
print(dict)
{'name': 'kim', 'address': 'seoul', 'age': '10'}
In [13]:
for key, value in dict.items():
print('key:', key, ",\tvalue: ", value)
key: name , value: kim key: address , value: seoul key: age , value: 10
In [14]:
data = [ 1, 3, 5, 7, 3, 7, 5, 8, 7]
counter = {}
for x in data:
if x not in counter:
counter[x] =1
else:
counter[x]+=1
print(counter)
{1: 1, 3: 2, 5: 2, 7: 3, 8: 1}
- couter를 for loop대신 collection 모듈 counter 클래스를 이용하여 사용가능
In [21]:
from collections import Counter
cnt = Counter(data)
print(sorted(cnt.items()))
[(1, 1), (3, 2), (5, 2), (7, 3), (8, 1)]
True/ False¶
- True -> 1
- False -> 0
In [23]:
print('True:', bool(1))
print('False:', bool(0))
True: True False: False
파일 입출력¶
open(): 파일 객체를 만들때
- r : 읽기 모드
- w : 쓰기 모드
- a : 추가 모드( 파일의 마지막에 새로운 내용 추가)
close(): 파일객체를 닫을때
write(): 파일에 데이터를
readline(): 각 줄을 읽을 때 사용하며 각 죽을 그대로 읽기 때문에 줄바꿈 기호를 제거하기 위해 strip()을 사용할 수 있음
read(): 문서 파일 전체 내용을 하나의 문자열로 반환
주로 with 구문과 함께 쓰이며 파일객체를 자동으로 열고 닫을 수 있어 close함수를 쓰지 않아도 됨
with open(파일이름, 파일모드) as f: f를 이용하는 코드
In [24]:
f = open('example.txt', 'w')
f.close()
In [26]:
f = open('example.txt', 'w')
data = 'data'
f.write(data)
f.close()
In [27]:
f = open('example.txt', 'r')
line =f.readline()
print(line)
f.close()
data
In [29]:
file_name = 'example.txt'
with open(file_name, 'r') as f:
line = f.readline()
print(line)
data
In [32]:
import json
# 파일 읽기
def load_json(path):
with open(path, 'r', encoding='utf-8') as f:
return json.laod(f)
# 파일 저장
def save_json(path, obj, sort_keys=True)-> str:
# 파일을 정상적으로 저장하였을 때
try:
with open(path, 'w') as f:
json.dump(obj, f, sort_keys=sort_keys)
msg = f"Json saved {path}"
# 파일이 저장 에러
except Exception as e:
msg = f"Fail to save {e}"
return msg
CSV파일¶
- index=False로 하지 않으면 저장시 인덱스가 생성되어 저장됨
In [ ]:
import pandas as pd
# 파일 읽기
def load_csv(path):
return pd.read_csv(path)
# 파일 저장
def save_csv(path, obj, index=False):
try:
obj.to_csv(path, index=index)
except Exception as e:
return f"Fail to save {e}"
728x90