def add(x, y):
return x + y;
add(1, 2); # 3
파이썬에서 함수 정의
(lambda x, y : x + y) (10, 20) # 30
람다 형식을 이용해 이렇게 표현할 수 있음.
lambda (매개변수) : (실행문)
t = lambda x : x * 2 + 1
t(6) # 13
t = lambda x : print("test : {}".format(x+3))
반복문
for문은 list형 자료 작성 시에도 활용 가능하다.
x = [i ** 2 for i in range(10)]
x # [[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
while문으로 커피가 떨어지면 판매를 중단하고 "판매 중지"라는 문구를 보여준다.
coffee = 5
money = 300
while money:
print("돈을 받았으니 커피를 줍니다.");
coffee = coffee -1;
if not coffee:
print("판매 중지");
break;
continue를 이용해 홀수만 출력하기
a = 0
while a < 10:
a = a + 1
if a % 2 == 0: continue
print(a)
String 활용
s = "hello"
print(s.capitalize()) # 첫번째 문자 대문자로 변환
print(s.upper()) #모든 문자 대문자 변환
print(s.replace('l', '(ell)')) # 문자 대체
print(' world'.strip()) # 빈 공백 제거
list 사용
xs = [3, 1, 2]
print(xs, xs[2])
print(xs[-1])
xs[2] = 'foo'
print(xs) # [3, 1, 'foo']
xs.append('abc')
print(xs) # [3, 1, 'foo', 'abc']
x = xs.pop()
print(x, xs) # abc [3, 1, 'foo']
Slicing의 사용
: 파이썬 리스트의 일부에만 접근하는 문법
nums = list(range(5))
print(nums) # [0,1,2,3,4]
print(nums[2:4]) #[2,3]
코드에서 볼 수 있듯이, 지정한 인덱스에서 마지막 인덱스의 앞의 값까지 담기게 된다.
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal) # cat dog monkey (개행되어 출력)
for idx, animal in enumerate(animals):
print('#{}: {}'.format(idx + 1, animal))
#1 : cat
#2 : dog
#3 : monkey
파이썬의 enumerate 함수를 이용해 리스트의 요소 뿐만 아니라 인덱스까지 한 번에 출력할 수 있다.
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(i ** 2)
print(squares)
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares) #[0, 1, 4, 9, 16]
코드를 간결화하여 sqaures 리스트를 초기화할 수 있다.
Dictionaries
Java의 Map과 유사하게 key, value 쌍을 저장한다.
d = {'cat': 'cute', 'dog': 'furry'}
print(d[0]) # ERROR 인덱스 접근 불가
print(d['cat']) # key로 접근 가능
print('cat' in d) # true
d['fish'] = 'wet'
print(d['fish']) # wet
print(d)
# {'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}
print(d['monkey']) # ERROR 'monkey' not a key of d
# key가 존재하지 않을 때 출력할 default값을 설정하여 get
print(d.get('monkey', 'N/A') # N/A
print(d.get('fish', 'N/A')) # wet
# del 명령어로 dictionary의 'fish' key와 그에 해당하는 value를 삭제
del d['fish']
print(d) # {'cat' : 'cute', 'dog' : 'furry'}
print(d.get('fish', 'N/A')) # N/A
d = {'person' : 2. 'cat':4, 'spider' : 8}
for animal, legs in d.items() :
print('A {} has {} legs'.format(animal, legs))
"""
A person has 2 legs
A cat has 4 legs
A spider has 8 legs
"""
d.items() 함수를 이용해, 딕셔너리의 key와 value가 각각 animals, legs에 저장된다.
Set
순서가 없고 서로 다른 요소 간의 모임
animals = {'cat', 'dog'}
print('cat' in animals) # True
print('fish' in animals) # false
animals.add('fish')
print(animals)
print('fish' in animals)
print(len(animals))
animals.add('cat')
print(len(animals))
animals.remove('cat') # animals Set에서 cat지우기
print(len(animals))
Tuples
요소 간 순서가 있으며, 값이 변하지 않는 리스트이다.
t = (5, 6)
print((t)) # (5, 6)
t[1] = 0 // Cannot change tuple values
'Major Study > Artificial Intelligence Application' 카테고리의 다른 글
인공지능 응용 실습) KNN (0) | 2022.04.18 |
---|---|
Numpy 기초) Numpy 사용하기 & Data Split (0) | 2022.04.18 |
최적화 기법(Optimization) Linear/SVM/SoftMax Classifier (0) | 2022.04.16 |
선형 회귀(Linear Regression)의 개념과 Prediction (0) | 2022.04.03 |
Supervised Learning(지도 학습)의 개념 (0) | 2022.04.03 |