• 정수(int), 소수(float), 복소수(complex), 참거짓(bool,True,False), 문자(str)
'a',"hello"
# str이 tuple로 묶여있음
('a', 'hello')
  • 자료의 형태를 알고 싶을 때
type(True)
bool
  • 자료형 변환
int()
0
str()
''
bool()
False
int(1)
1
int(1.3)
1

그런데 소수점 떼는 방법에는 여러가지가 있음

import math
math.ceil(i) # 소수점 아래 다 올려버러기
math.floor(i) # 소수점 아래 다 내리기
math.trunc(i) # 소수점 아래 다 버리기
# 또는 round(a,b)를 통해서 원하는 자릿수까지 반올림 처리 할 수도 있다. 
# 그런데 사실 그냥 int로 다 버리는 방법도 있음
import math 
print(math.trunc(2.345))
print(int(2.345))
2
2
round(2.345,2)
# 소수점 아래 둘째자리까지 반올림해라
# 즉 소수점 아래 둘째자리까지 살아남는 거
2.35
  • str -> int 또는 float
int('1')
1
float('3.14') 
3.14
 
float('-inf')
-inf
complex(1)
(1+0j)
complex(3+5j)
(3+5j)
complex(3,5.5)
(3+5.5j)
complex('1+3j')
(1+3j)
  • int -> str
str(1)
'1'
str(2+5j)
# 괄호랑 +,j모두 원소 하나하나로 반환
'(2+5j)'
bool(-0.8)
True
bool(0)
False
bool(554)
True

0 제외하고 전부 True 처리

bool('')
False
bool(123)
# 0이 아닌 다른 수는 모두 True
True
bool('aasdss')
True
bool(0)
False
bool(float('inf'))
True
float('inf'),bool('-inf'),complex('inf')
(inf, True, (inf+0j))

연산

1+1,3-2,5*2,5/2
(2, 1, 10, 2.5)
5//2
2
5%2
1
divmod(5,3)
# 원소 2개인 tuple로 들어감
(1, 2)
abs(-232)
232
pow(5,4),5**4
(625, 625)
'asdasd'+'asdfeq'
'asdasdasdfeq'
'asdasd'*2
'asdasdasdasd'
  • 문자형이 다른 건 더할 수 없음
'asdasd'+str(235456)
'asdasd235456'
True+True
2
  • 비교 연산 => BOOL형태로 출력됨
1<0
False
2==3
False
1!=3
# 틀렸으니 맞다고 나올 것
True
# False라고 나오긴 함
# 그런데 is나 is not은 원래 자료형이 같고 다른지를 물을 때 사용함
type('123') is not type(True)
True

True and False
False
True and False and True
False
  • 거짓이 하나라도 있으면 거짓 처리

True or False
True
True or False or False
True
  • 참이 하나라도 있으면 참 처리

not True
False
  • 참과 거짓을 반대로 바꿔주는 기능 (by not)

100 and 5
5
True and 3
3
34 and True
True
34 and 2
2
  • 둘다 참일 경우(1이상인 수 혹은 True)일 땐 뒤에 걸 출력하는 것 같음

False and 3
False
0 and 100
0
  • and 연결에 Fasle가 하나라도 있으니 당연히 Fasle 쪽으로 출력됨

1 or 100
1
100 or 1
100
100 or 1 or 300
100
3 or 1 or 45 or 0
3
  • or 사용시엔 하나라도 참이 섞여있으면 그 중 맨 앞의 값을 출력
  • and 사용시엔 둘다 참일 경우 맨 뒤 값을 출력했음

1 and 0 and 100
0
  • 0(False)이 하나 있어서 0 출력

Bitwise :이진법

2 #십진법
2
bin(2) # 이진법
'0b10'
bin(3)
'0b11'
bin(12)
'0b1100'

& $\to$ and랑 헷갈리지 말자

10&6
2
  • 10과 6을 2진법으로 처리한 후 겹치는 자리만 뽑아낸 것
bin(10)
'0b1010'
bin(6)
'0b110'
bin(10&6)
'0b10'
10|6
# or와 다름
14
bin(10)
'0b1010'
bin(6)
'0b110'
bin(10|6)
'0b1110'
10^2
# 제곱 아님
# 10**2 또는 pow(10,2)로!
8
print(10**2)
print(pow(10,2))
100
100
bin(6)
'0b110'
bin(10)
'0b1010'
bin(10^6)
'0b1100'
bin(6)
'0b110'
bin(6<<2)
'0b11000'
bin(6>>2)
'0b1'
6>>2
1

변수

a=1
a
1
print(a)
1
b=3.225
type(b)
float
b=546548
b
546548
d=True
print(d)
True
b=a
b # 다른 변수로 해당 변수를 업데이트 할 수 있음
1
a=5
a
5
b
1

a가 바뀌어도 a로 업데이트 된 b는 그 전 a의 자료인 1로 그대로 유지 중

length=2
width=3
area=length*width
x=1
y=2*x
y
2
a=3
bin(a)
'0b11'
a.bit_length()
2
b=10
bin(b)
'0b1010'
b.bit_length()
4
c=1+2j
d=c.conjugate()
d
(1-2j)
d.imag
-2.0
c
(1+2j)
c.real # c 안의 실수
1.0
c.imag # c 안의 허수
2.0
a=1
a+=1 # a에 있는 값을 1만큼 올려서 저장
a
2
a-=10
a
-8

  • 문자열 내장 함수?
name='tom'
name.capitalize() # 맨 앞을 대문자 처리
'Tom'
name.count('2') #name이라는 변수에 2 몇개?, 대문자 소문자도 구별해서 카운트함
0
name.count('o')
1
name.split('o') 
# 'o' 없애고 'o'기준으로 나눠줌
# 리스트 형태로 저장됨
['t', 'm']
a=name.split('o')
type(a[0])
str
type(a)
list
a[1]='o'
a.append('m')
# list에서 가능함
a
['t', 'o', 'm']
# split은 str에서만 가능한가봄
# split 자체가 어떤 값을 기준으로 나눠서 list로 반환해주는 것이기 때문에 list에선 사용 X
'asdasd'.capitalize()
'Asdasd'

  • 백 슬러시 \ 다음에 심볼 적으면 심볼로 인식
a='i\'m student'
a
"i'm student"

input('enter: ')
'55'
a=input('enter: ')
a # str으로 저장됨
'55'
type(a)
str
age=int(input('enter your age: '))
age # int로 저장됨
564
del age
a=1
b=3
a==b
False
a.__eq__(b) # a==b랑 동일
False
a,b=10,134
# tuple을 의미하는 건 아님
  • a와 b 교환
a,b=b,a

str=1
str
1
# error 발생 => 원래 내장 함수인 str이 위셀에서 변수명으로 저장됨으로써 함수기능을 상실함

즉 파이썬과 지원되는 함수와 동일한 변수명 사용하면 안 됨

del str

Container

list. tuple. set. frozenset. dictionary.
  • list (수정 가능)
asd=[10,25,'123',True]
# 자료형 혼합 가능
asdasd=list([10,25,'123',True])
# 이 방법으로 list만들 땐 꼭 대괄호로 묶어줘야 함
  • tuple (수정 불가)
qwe=(12,22.1,'qwe')
qwe
(12, 22.1, 'qwe')
qweqwe=tuple([1,2,3,'asdasd',True])
# 대괄호로 묶어줘야함
qweqwe
(1, 2, 3, 'asdasd', True)
  • list와 tuple은 sequence자료형
vip_names = ['c','d','a']
vip_names[0]='랴차'
vip_names
['랴차', 'd', 'a']
  • list는 자료 수정 가능
  • 하지만 tuple은 자료 수정이 안 된다

slicing

my_list1=[12,123,123,123,42,14]
my_list1[0:2] #0,1번 원소 추출
[12, 123]
my_list1
[12, 123, 123, 123, 42, 14]
my_list1[:] # 모든 자료
[12, 123, 123, 123, 42, 14]
my_list1[::2] # 모든 자료형태에서 2단위로 추출
[12, 123, 42]
my_list1[:3:2] # 0,1,2원소를 2단위로 추출
[12, 123]
my_list1
[12, 123, 123, 123, 42, 14]
my_list1[-1]
14
my_list1[-5:-1] # -1값은 해당 X
[123, 123, 123, 42]
my_list1[-5]
123
my_list1
[12, 123, 123, 123, 42, 14]
my_list1[-1::-1] # 뒤에서부터 가져올 땐 단위도 - 붙여줘야 함
[14, 42, 123, 123, 123, 12]
my_list1[-1:2:-1] 
# 두번째 인덱스 전까지 뒤로 추출
# 시작을 -1로 해서 2로 끝났으니 마지막에 호출 단위를 -붙여서 꼭 해줘야함
# 호출단위를 안 쓰거나 플러스로 하면 아무것도 출력 안 됨
# 주의 !!!
[14, 42, 123]
my_list1
[12, 123, 123, 123, 42, 14]
my_list1[-4:5:1]
# -4와 5중 list에서 원소로서 뭐가 먼저 입력되어있는지에 따라 마지막에 -1로 출력할 것인지 1로 출력할 것인지 달라짐
# 1말고 -1로 출력하면 아무것도 출력 안 됨
[123, 123, 42]
my_list2 = [[1,2,3,4,5],[1232]]
my_list2
[[1, 2, 3, 4, 5], [1232]]
my_list4 = [[1,2,3,4,5],
            [1,2,3,4],
            "ㅁㄴㅇㅁㄴㅇ"]
# 이렇게 복잡할 땐 한줄 내려서 입력해도 가능하다
my_list4
[[1, 2, 3, 4, 5], [1, 2, 3, 4], 'ㅁㄴㅇㅁㄴㅇ']

  • 리스트 중첩 가능
my_list4[0]
[1, 2, 3, 4, 5]
my_list4[0][3]
4
my_list4[1][::2]
[1, 3]
my_list5 = [ [10,20,[100,200,300]], [40,50,60] ]
my_list5[0][2][2] # 리스트 중첩 후 원소 불러오기
300

차이점!!!!!

a=[1,2]
b=[123,2323]
a+b
[1, 2, 123, 2323]
import warnings
warnings.filterwarnings('ignore')
import numpy as np
np.array([1,2]) + np.array([123,2323])
array([ 124, 2325])
  • 즉 리스트는 리스트끼리 더해줘도 리스트 원소 자체의 덧셈이 아니라 리스트와 리스트의 덧셈개념으로 연결해주는 것인데 넘파이는 연결이 아니라 각 원소끼리의 합을 해줌
  • 그런데 넘파이에서 차원이 맞지 않으면 작동하진 않는다.

a=[[1,2],[1,2,3]]
b=[[1,2,'s'],[1,2,3]]
a+b
[[1, 2], [1, 2, 3], [1, 2, 's'], [1, 2, 3]]
a*2
[[1, 2], [1, 2, 3], [1, 2], [1, 2, 3]]

old_a=[1,2,3]
new_a=old_a
old_a[0]=2
new_a[0]
2
  • new_a=old_a는 같은 메모리를 공유함으로써 new_a 와 old_a 모두 동시 수정됨
  • 대책은?
new_a=old_a.copy()
new_a[0]=1
new_a
[1, 2, 3]
old_a
[2, 2, 3]

  • extend
a=[1,2,3]
b=[2,3,4]
a+b
[1, 2, 3, 2, 3, 4]
a.extend(b)
a
['asdf', 'k', 2, 3, 4]
a=[1,2,3]
b=[2,3,4]
a+=b
a
[1, 2, 3, 2, 3, 4]
asd=['asds','sdasd','sd']
  • 이 자료에 원소 추가하기
asd.append('e')
asd
['asds', 'sdasd', 'sd', 'e']
  • str에선 안 된다!!
asd.remove('e')
asd
['asds', 'sdasd', 'sd']
  • 인덱스로 원소 지우기 -> pop사용
asd.pop(1)
# 'sdasd'가 삭제됐음
# 'sdasd'가 삭제됐다고 반환하면서 알려주는 이 형식도 사용할 때가 있음
'sdasd'
asd
['asds', 'sd']
  • 초기화
asd.clear()
asd
[]
asd.insert(0,'sds')
asd
['sds']
asd.index('sds') # 자리 번호 알기
0
asd.count('sds') # 몇번 들어가 있는지
1
a=['a','c','f','b']
a.insert(2,'두번째 자리')
a
['a', 'c', '두번째 자리', 'f', 'b']
a.sort()
# 정렬중
a # 숫자와, bool도 정렬가능
['a', 'b', 'c', 'f', '두번째 자리']

지금 list a에는 원소가 다섯개 있는데 전부 자료형 str이다

그런데

a=[2,'False']
# 이렇게 자료형이 섞여있으면 불가능
# 지금 False가 bool형태가 아니라 str형태로 들어가있음
asf=[True,123333,0,134]
asf.sort()
asf # 자료형이 안 섞여있으면 가능
[0, True, 134, 123333]
qwe=[1,2,3]
qwe.reverse()
qwe
[3, 2, 1]
qwe[-1::-1] # reverse와 동일
[1, 2, 3]

  • set
my_set1={1,2,3}
my_set2={False,5,54}
my_set3={False,5,5}
my_set3 
{False, 5}

집합처럼 중복 원소는 하나로 처리 BUT 리스트는 중복 원소 생략 안 하고 그대로 넣어준다

set은 인덱스를 지원하지 않음

alist=[2,3,4,1324]
my_set32412=set(alist)
my_set32412
{2, 3, 4, 1324}

list에선 append와 insert였음

my_set32412.add(2525)
my_set32412
{2, 3, 4, 1324, 2525}
my_set32412.update([546])
my_set32412
{2, 3, 4, 546, 1324, 2525}
  • 이렇게 순서대로 들어가게 됨
my_set32412.discard(1324)
my_set32412
{2, 3, 4, 546, 2525}
my_set32412.remove(2525)
my_set32412
{2, 3, 4, 546}

즉 discard와 remove는 동일하나 remove는 이미 없는 값을 또 삭제하려 할 때 error메세지를 보여줌


a={1,2,3,5}
b={6,5,55,4}
a or b
{1, 2, 3, 5}
b or a
{4, 5, 6, 55}
  • 앞에 있는 거 출력

print(bin(2))
print(bin(4))
0b10
0b100
2|4
6
print(bin(2|4))
0b110

이거(이진수 처리)랑 다른 거


a|b
{1, 2, 3, 4, 5, 6, 55}
a.union(b)
{1, 2, 3, 4, 5, 6, 55}
b.union(a)
{1, 2, 3, 4, 5, 6, 55}
a&b # 교집합
{5}
a.intersection(b)
{5}
b.intersection(a)
{5}
a-b
{1, 2, 3}
a.difference(b)
{1, 2, 3}
b.difference(a)
{4, 6, 55}

  • 이것도 원래는 이진법 처리할 때 사용되는 기호임
  • 따라서 숫자를 제곱할 때는 ^이걸 사용하면 안 되고 ** 사용하던가 pow를 사용했어야 했음
a^b # 겹치는 거 빼고 출력
{1, 2, 3, 4, 6, 55}
a.symmetric_difference(b) ## 겹치는 거 빼고 출력
{1, 2, 3, 4, 6, 55}
b.symmetric_difference(a) # 겹치는 거 빼고 출력
{1, 2, 3, 4, 6, 55}

a={1,2,3,4,5}
b={1}
b.issubset(a)  #b가 a의 부분집합?
True
a.issubset(b) # a가 b의 부분집합?
False
a.issuperset(b) # a는 b를 포함?
True
b.issuperset(a)# b는 a를 포함?
False

  • frozenset - 추가가 안됨, 어차피 set은 index가 없어서 수정은 안 됐으니까 수정이 안 되는 문제하곤 별개임
a=frozenset([1,2,3,4,5])
b=frozenset([4,5,6,7,8])
a|b
frozenset({1, 2, 3, 4, 5, 6, 7, 8})
a&b
frozenset({4, 5})
# 추가 불가
# frozenset이기 때문에
c=set([1,2,3,4])
a&c 
frozenset({1, 2, 3, 4})

asq=['qw','qwa','qwsd']
door1_list = ['qw']
door2_list = ['qwa']
door1_list in asq
False
  • 왜 false?
door1_list[0]
'qw'
door1_list[0] in asq
True
  • 이렇게 해야 True

all=set(asq)
all
{'qw', 'qwa', 'qwsd'}
d1=set(door1_list)
d2=set(door2_list)
d1.issubset(all)
True
d2.issubset(all)
True
d_combine=d1 |d2
d_combine
{'qw', 'qwa'}
d_combine.issubset(all) # 부분집합?
True
all-d_combine
{'qwsd'}

my_dict={'a':'qewqwe','b':'qewe','c':'qwqwe'}
  • dic => key,value로 이루어져있다
  • : 이 들어가면서 set이랑은 다름
type(my_dict)
dict
my_dict['c']
'qwqwe'

즉 따라서 순서는 중요하지 않음

number={'1':'12312123123','asas':'12313','asdad':'12323'}
number['asas']
'12313'
number.get('asas')
'12313'
number['asas']='fucking' # 자료 수정
number
{'1': '12312123123', 'asas': 'fucking', 'asdad': '12323'}
number.update({'1':'asdasdddd'}) # 자료 수정
number
{'1': 'asdasdddd', 'asas': 'fucking', 'asdad': '12323'}
'1' in number # key가 들어가있는지 안 들어가 있는지
True
'fucking' in number 
# key가 들어가있는지 안 들어가 있는지
# 그래서 value를 물어보면 다 Fasle로 출력하네
False
number.pop('1') # 삭제
'asdasdddd'
number
{'asas': 'fucking', 'asdad': '12323'}
number.clear()
number
{}

alist=[1,2,3,4,5]
atuple=(1,2,3,4,5)
aset={1,2,3,4,5}
len(alist) # 컨테이너의 값 개수를 알 수 있음
5
max(aset)
5
min(alist)
1
6 in atuple # 값 들어가있는지 체크하기
False
555 not in atuple
True

list unpacking

a=['a',23,'asf']
name=a[0]
age=a[1]
lan=a[2]
  • 이걸 한 번에 = list unpacking
name,age,lan=a
print(name)
print(age)
print(lan)
a
23
asf
  • 리스트 a에서 처음 원소만 자료로 받고 나머지는 그에 헤당한 자료형으로 남겨놓고 싶을 때
name, *rest = a

응용하면

*rest,name=a
name
'asf'
first,second,*rest=a
first
'a'
second
23
  • 또는
a
['a', 23, 'asf']
name, _, _ = a
_
'asf'
name
'a'
name, *_ = a
name
'a'
_
[23, 'asf']
  • underbar를 활용할 수도 있겠다.

a=range(0,21,2) # 20까지임, 그런데 2단위로
np.linspace(2,20,10)
array([ 2.,  4.,  6.,  8., 10., 12., 14., 16., 18., 20.])
  • 둘이 비교해보기

type(a)
range
a[2]
4
a.index(20)
10
a[10]
20
a[:5]
range(0, 10, 2)
a[-1]
20
list(range(10,51,10))
[10, 20, 30, 40, 50]
 
for i in range(5) : print(i)
0
1
2
3
4
for i in range(2,11,2) : print(i)
2
4
6
8
10
for i in range(10,2,-2) : print(i)
10
8
6
4
for i in range(10,1,-2) : print(i)
10
8
6
4
2