[컴퓨터 공학 기본과 파이썬] Python Programming

2022. 5. 30. 21:10AI/Codestates

728x90
반응형

정규표현식이란?

▶ Escape 문자

이스케이프 문자 이름
\n 줄 바꿈
\t
\b 백스페이스
\\ 백슬래시 ( \ )
\' 작은 따옴표 ( ' )
\" 큰 따옴표 ( " )

▶ Raw String

- Escape 문자를 문자열 그대로 사용하고자 한다면 Raw String을 사용하면 됨

- 출력할 문자열 앞에 r을 붙여주면 됨

다양한 메소드의 활용

▶ rjust(width, [fillchar])

원하는 문자를 따로 지정하고, 다른 문자열로 앞 부분을 채워 줄 수 있음

#"002"
print("2".rjust(3,"0"))
 
#"50000"
print("50000".rjust(5,"0"))
 
#"00123"
print("123".rjust(5,"0"))
 
#"aa123"
print("123".rjust(5,"a"))

▶ zfill(width)

#"002"
print("2".zfill(3))
 
#"50000"
print("50000".zfill(5))
 
#"00123"
print("123".zfill(5))

▶ split & startswith & endswith & replace

string_ = "Hello, I am Jack and I am a data scientist"

# ["Hello,", "I", "am", "Jack", "and", "I", "am", "a", "data", "scientist"]
string_.split(" ")

# True 시작하는 문자열이 맞는지
string_.startswith('Hello')

# True 끝나는 문자열이 맞는지
string_.endswith('scientist')

# "Hello, I am John and I am a data scientist"
print(string_.replace("Jack", "John"))
print(string_)

얕은 복사 (copy())

# 내장함수 copy
fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy()
fruits_copy

# 할당
a = {'a': 5, 'b': 4, 'c': 8}
b = a
del b['a']
print(b)
print(a)

# copy 라이브러리
import copy
a = {'a': 5, 'b': 4, 'c': 8}
b = copy.copy(a)
del b['a']
print(b)
print(a)

▶ 깊은 복사 ( Deep Copy )

- 깊은 복사는 매부에 객체들까지 새롭게 copy 되는것

- 완전히 새로운 변수를 만드는 것이라고 볼 수 있음

import copy
list_var = [[1,2],[3,4]]
list_var_deepcopy = copy.deepcopy(list_var)

반복문과 조건문

# 일반적인 반복문 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
for i in range(len(a)):
   print(a[i],b[i])
   
# zip 함수 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = zip(a,b)
print(list(c))

# 반복문과 zip 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [100,200,300,400,500]
for x,y,z in zip(a,b,c):
   print(x,y,z)

# break
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
    if(x==3):
        break
    else:
        print(x)
        
# continue
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
    if(x==3):
        continue
    else:
        print(x)

에러상황파악 ( Error & Warning )

# IndentationError 들여쓰기 에러

def print_list(list):
for item in list: # 에러 확인 및 해결필요
print(item)

# SyntaxError

123ddf

# KeyboardInterrupt

while True:
  pass

# TypeError

print(1) / 232

a,b = 0
print(a,b)

# ZeroDivisionError

value = 2/0

# 경고(warning)
def A():
  a = 0
  c =0
  print(a,c,) # 경고는 명시적으로 보이지 않지만, 메모리 비효율/휴먼 에러 등이 발생할 수 있다.

람다란?

- 람다는 구독성이 좋기때문에 함수 표현식의 규모가 작을 때 사용하는 것이 좋음

- 람다 함수의 장점은 함수 객체를 반환함

# map과 lambda
spelling = ["test1", "test2", "test4 test5", "test3"]
shout_spells = map(lambda item: item + ('!!!'), spelling)
shout_spells_list = list(shout_spells)
print(shout_spells_list)

# filter와 lambda
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']
result = filter(lambda member: len(member) > 6, fellowship)
result_list = list(result)
print(result_list)

# functools 모듈 사용
from functools import reduce

stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']
result = reduce(lambda item1, item2:  item1+item2, stark)
print(result)

파이썬 프로그램 구성

728x90
반응형