필기 정리 - python

조형찬·2023년 2월 6일
0

필기 정리

목록 보기
7/11

  • python 환경설정 ★

python.org에서 다운로드 받기
'path추가' 항목을 선택하여 다운진행
vscode 확장프로그램에서 python다운 후 c관련된 거는 다 사용안함으로 해두기

파일명.py로 파이썬 파일 생성 가능
ctrl +F5로 실행 (실행이 안될 경우 utf-8로 바꿀것)

IDLE(파이썬 작동가능한 에디터)
option - config : IDLE설정가능


  • python 기본내용

인터프리터 형 - 한 줄 씩 쓰고 해석, 쓰고 해석함(매번 컴파일 한다고 생각하면 됨)

ctrl+/ 주석을 의미하는 #가 나옴


  • python 줄바꿈 \n

\n는 파이썬에서도 줄바꿈 기호다.
변수명만 눌러서는 반영이 안되고
print(변수명)을 해주면 \n가 반영된다.
(''' 내용 ''')으로 감싼 상태에서 줄바꿈을 해줘도 반영된다.

a="a \n b"
print(a) 
//
a
b

b='''a
b
c
'''
print (b)
//
a
b
c 

한칸씩 줄바꿈되어 출력 되어 나타난다.


  • 변수 출력
a="python"
b="is fun"
a*3 //'pythonpythonpython' 출력됨
a+b //'python is fun' 출력됨

  • type

데이터가 무슨 형인지 알려줌

type(7)
//<class 'int'>
type(2.5)
//<class 'float'>
type(7 + 3j)
//<class 'complex'> 여러형 섞인 경우
type(True)
//<class 'bool'>
type("abc")
//<class 'str'>

  • 인덱스[음수]일 때
) a="abcde"
a[-1] =e
a[-2] =d
a[-0] =a

인덱스 안에 음수일 때 뒤에서 부터 센다.
cf)[-0]은 [0]과 같음


  • 문자열 슬라이싱
) a="abced"
a[0:3] = abc //인덱스 0이상 부터~인덱스 3미만인 것을 선택하라는 뜻

a="Life is too short, You need python"
print(a[0:5]) //Life
print(a[12:7]) // 안나옴
print(a[19:]) //You need python 인데스 19에서 끝까지
print(a[:17]) //Life is too short 처음에서 인덱스 17까지
print(a[:]) //Life is too short, You need python 전부다
print(a[19:-7]) //You need 

  • 리스트 안에 다른 리스트 포함
) 
a=[1,2,3,[4,5],6,7]

print(a[0]) //1
print(a[3]) //[4,5]
print(a[4]) //6
print(a[3][0]) //[4]

리스트는 배열과 비슷하지만 배열은 아니다.
따라서 a는 2차원 배열과 유사하지만 1차원 배열처럼 적어도 된다.예) a[0]
값이 필요한 경우에만 2차원 배열처럼 적어주면 된다.
예)a[3][0]
리스트 안에 들어가는 내용의 자료형이 달라도 된다.(문자, 숫자,특수기호 등)


  • 길이 len()함수
)
mylist = ['apple','banana','cherry']
print(len(mylist)) //3

  • 리스트에 사용되는 연산 ★

.append() // 끝에 삽입

)
mylist = ['apple','banana','cherry']
mylist.append('orange')
print(mylist) //['apple', 'banana', 'cherry', 'orange']

.insert() //지정한 곳에 삽입

)
mylist.insert(1,'melon') //인덱스 1번 자리에 넣어라
print(mylist) //['apple', 'melon', 'banana', 'cherry', 'orange']

.extend() //확장해서 뒤에 삽입

)
vegilist=['abc','def']
mylist.extend(vegilist)
print(mylist) //['apple', 'melon', 'banana', 'cherry', 'orange', 'abc', 'def']

.remove() // 리스트내용 삭제

)
mylist.remove('banana')
print(mylist) // ['apple', 'melon', 'cherry', 'orange', 'abc', 'def']

pop() // 맨 뒤 없어짐

)
mylist = ['apple','banana','cherry']
mylist.pop() 
print(mylist) //  ['apple', 'banana']

pop(숫자) //해당 인덱스 값 없어짐


mylist = ['apple','banana','cherry']
mylist.pop(0)
print(mylist) //['banana', 'cherry']

del 리스트명[인덱스번호] //해당 인덱스 값 없어짐

)
mylist = ['apple','banana','cherry']
del mylist[0]
print(mylist) // ['banana', 'cherry']

.clear() //해당 리스트 안의 모든 값 없어짐. 단, 리스트는 존재

)

mylist = ['apple','banana','cherry']
mylist.clear()
print(mylist) // []

  • 서로다른 자료형 출력
)
a=5
b="Smith"
print(a,b)
print(a+b) //출력 안됨(숫자, 문자 섞여있기 때문)
print(str(a)+b) //5Smith 숫자 5를 문자형으로 바꾸었기 때문에 출력 됨

  • 데이터형 종류

숫자형 int float complex
문자형 str
sequence 형 list


  • 대문자, 소문자 변경
)
x="Hello World"
print(x.upper()) //HELLO WORLD
print(x.lower()) //hello world

  • .split() 나누어서 리스트로 반환
)
x="naver daum"
print(x.split(' ')) //['naver', 'daum']

중간에 공백이 있어서 그 공백을 기점으로 나누고 이를 리스트로 반환한 것이다.

y="naver,daum"
print(y.split(',')) // ['naver', 'daum']

중간에 ','가 있어서 그 기점으로 나누고 이를 리스트로 반환한 것이다.

  • .strip 공백제거
)
a="   Hello,World   "
print(a.lstrip()) //Hello,World    왼쪽 공백 제거
print(a.rstrip()) //    Hello,World오른쪽 공백 제거
print(a.strip()) //Hello,World앞 뒤 공백 제거

cf)중간에 있는 공백은 제거가 안된다.


  • .replace() 내용 바꾸기
)

i="Hello, World"
print(i.replace('H','J')) //Jello, World H를 J로 바꿈
print(i.replace('W','K')) //Hello, Korld W를 K로 바꿈

여기서 print(i)는 그대로 //"Hello, World"를 출력한다.
하지만 a=i.replace('W','K')로 할당해주고
print(a)를 하면 //"Hello, korld"가 출력 된다.

  • casting(형변환) 할 때 ★

z="3"
int(z) (o) / (int)z (x)
괄호의 위치에 주의한다.

  • .format()
1) {} .format 사용
quantity=3
itemno=567
price=49.95

yourorder="I want {} pieces of item for {} dollars"
print(yourorder.format(quantity,itemno))
//출력 : I want 3 pieces of item for 567 dollars

yourorder="I want to pay {2} dollars for {0} pieces of item{1}" //인덱스 값 부여
print(yourorder.format(quantity,itemno,price))
//출력 :I want to pay 49.95 dollars for 3 pieces of item567 (인덱스 값에 맞추어 출력)

//print("{}").format()형태 사용
//{}안의 내용을 `format()`` 안의 내용으로 바꾸는 기능을 한다고 생각하면 된다.2) % 사용
print("I eat %d apples." %  3) //I eat 3 apples. //숫자
print("I eat %s apples." % "five") //I eat five apples. //문자
number=3
print("I eat %d apples." %number) //I eat 3 apples. //변수

예3) f{} 사용
name="hong"
age=30
house="Suwon"
print(f"나는 {name}이고 나이는 {age} 집은 {house} 입니다") 
//3.6버전 이상 가능
//print(f"{}") 형태 사용
//출력 : 나는 hong이고 나이는 30 집은 Suwon 입니다

예4) f{}사용
d= {'name':'홍길동','age':30}
print(f'나의 이름은{d["name"]}입니다. 나이는 {d["age"]}') //변수d안의 객체를 선택
//나의 이름은홍길동입니다. 나이는 305) '{}' 보이게 하기
print("{{and}}".format()) 
//출력 : {and}

  • 정렬
)
print("{0:<10}".format("hi")) //왼쪽정렬, 문자열 10자리
print("{0:>10}".format("hi")) //오른쪽정렬, 문자열 10자리
print("{0:^10}".format("hi")) //가운데 정렬
print("{0:=^10}".format("hi")) //가운데 정렬, 공백을 =로 채움
print("{0:!<10}".format("hi"))// 왼쪽정렬, 공백을 !로 채움

출력 결과

hi
        hi
    hi
====hi====
hi!!!!!!!!

  • 문자열 함수
)
a="hobby"
print(a.count('b'))  //2 'b'가 몇 개인가
print(a.find('y')) //4  'y'가 몇 번째인가
print(a.find('k')) // -1 'k'를 못찾았으면 -1

a="Life is too short"
print(a.index('t')) // 8 't'가 몇 번째인가
print(a.index('k')) // 'k'를 못찾으면 오류남(.find는 -1 출력)

  • 연산자 종류

python에서는 ++,-- 등 증감연산자는 사용불가능하다.


  • python에서의 '참조' 개념 ★
)

x=[1,2,3,4]
y=x
print(x) //[1, 2, 3, 4]
print(y) //[1, 2, 3, 4]
x[1]=10
print(x) //[1, 10, 3, 4]
print(y)//[1, 10, 3, 4]

포인터와 참조의 개념은 유사하다.
x[1]의 내용만 바꿨는데 y의 내용도 바뀐것은
y가 x의 값을 복사하는 것이 아니라 x가 가리키는 부분을 y도 같이 가리키는 참조형이기 때문이다.
따라서 x의 내용만 바뀌었지만 같은 곳을 가리키던 y를 출력하면 바뀐 내용이 나오는 것이다.


  • input()
)
input() (x)   //input()만 적으면 실행 안됨
x=input()  (o) // x라는 변수에 input()을 주면 사용자에게 내용을 입력 받음
a=input("문자를 입력하세요 :") //"문자를 입력하세요 : 출력 후 사용자에게 입력을 받음
입력받은 값의 형태를 적어주는 것이 좋다.) a=str(input("문자를 입력하세요 :")) // 문자형 자료를 a에 입력받음

  • if문 ★
1)

print("나이를 입력하세요")
age =int(input())
if age>18:             //':'콜론 사용 필요
    print('성인')       //들여쓰기 중요
else : 			       //':'콜론 사용 필요
    print('미성년')     //들여쓰기 중요
    	print('미성년') //한번더 들여쓰기하면 실행안됨
		               //들여쓰기를 한다는 건 뭔가 달라진다는 것 의미(if,else).2)
money=1000
card =True
if money>3000 or card:  //money가 3000보다 많거나 card가 있는가?
    print("택시를")
    print("타고")
    print("가라")
else :
    print("걸어가라")
    
// 출력 : 택시를 타고 가라 (card가 True기 때문)

if문은 :사용과 들여쓰기가 중요하다
python에서의 else ifelif:다.


  • x in s, x not in s
)
print(1 not in[1,2,3]) // False
print(1 in[1,2,3])  // True
print('a' in ('a','b','c')) // True
print('j' in 'python') // False

pocket =['paper','money','cellphone']
if 'money' in pocket:pass // pass는 아무것도 하지 않고 지나가라는 의미
else: print("카드를 꺼내라")

x in s // s안에 x가 있으면~
x not in s // s안에 x가 없으면~


  • turtle ★
1)

import turtle      //turtle 모듈 다운(제일 먼저 해주어야 함)
t=turtle.Pen()     //t라는 변수에 turtle.Pen() 저장
t.reset()          //화면 지우고 초기화
t.color(1,0.5,0)   //주황색을 쓰겠다
t.begin_fill()     //안을 채우겠다(주황색)
t.circle(100)      //사이즈 100의 원을 그리겠다
t.end_fill()       //채우기를 끝내겠다(주황색)2)
import turtle
t=turtle.Pen()
t.speed(0)              // 그리는 속도 조정 (0: 가장빠름 3: 느림 6: 평범 1: 매우느림)
turtle.bgcolor('black') // 배경색을 검정색으로 (t.bgcolor가 아님)
colors=['red','yellow','blue','green','orange','purple','white','gray'] // 선색깔 항목 설정
sides= int(turtle.numinput("원의 갯수","(1-8)를 선택하세요")) 
                        //사용자가 고르도록 함 
                        //turtle.numinput("팝업창 제목","팝업창 내용")의 형식 중요.(안에 두가지 내용) 
for x in range(180):
    t.pencolor(colors[x%sides]) // x%sides는 0~7사이 값이다. cf)  x%30,1,2로 총 세가지
    t.circle(x)
    t.left(360/sides+1)
    t.width(x*sides/200) //선의 너비에 관여함.

  • for x in range( , ):
1)
for x in range(1,38): //for안의 내용을 37번 반복하라 
    t.forward(100)    // 100만큼 전진
    t.left(85)        //왼쪽 85도만큼 방향 전환

예2)
for x in range(1,19):
       t.forward(100)
       if x % 2 ==1:    //홀수일 때
       		t.left(225)
       else:            //짝수일 때
        	t.left(175)


for x in range(시작 숫자,끝나는 숫자,간격): 
	반복 코드 //들여쓰기
	반복 코드 //들여쓰기

//함수의 원형
//시작 숫자는 포함되지만, 끝나는 숫자는 포함되지 않는다.) (1,10)일때 1~9까지
//이상과 미만의 개념으로 이해하면 된다. 

for x in range(1,11)
for x in range(10)
둘은 모두 10번 반복한다.

  • dictionary ★
)

a={Key1:Value1,Key2:Value2,...} // dictionary의 기본형

dictionary는 key값에 인덱스형을 사용하지 않는다.

)
a={1:'a',2:'b'} 일때
a[1] // 인덱스번호 1이 아니라 key 이름이 1인 것의 Value를 의미하므로 a가 나온다

key에는 변하지 않는 값이 들어가야 하므로 list형 혹은 dictionary형으로는 쓸 수 없다.
단, Value에는 list형으로 들어가도 무관하다.

)
a={[1,2]:'a'} (x)
a={'a':[1:2]} (o)

  • dictionary를 만드는 함수dict()
)
thatdict= dict(name="John",age=32,country="Norway")
print(thatdict) //{'name': 'John', 'age': 32, 'country': 'Norway'}

thatdict라는 변수에 dictionary를 만드는 결과가 나옴.


  • dict() 함수 값의 추가, 제거
1)
thatdict= dict(name="John",age=32,country="Norway")
print(thatdict)

x=thatdict.get("name")
print(x)   //John thatdict의 key "name"의 Value값 출력


thatdict["name"]="Smith"
print(thatdict) 
//{'name': 'Smith', 'age': 32, 'country': 'Norway'} 
//Key "name"의 Value를 "Smith"로 변경 
//(key "name"이 없었다면 생성하여 Value"Smith"와 함께 추가한다.)

thatdict.update({"country":"korea"})
print(thatdict) 
//{'name': 'Smith', 'age': 32, 'country': 'korea'} 
//key "country"의 Value를 "korea"로 변경

예2)
thisdict ={
    "brand" : "Ford", 
    "model" : "Mustang",
    "year" : 2023
}


thisdict["colors"] ="red" //thisdict에 Key는"colors",Value는 "red"를 넣어줌
thisdict.update({"color":"red"}) //thisdict에 Key는"colors",Value는 "red"를 넣어줌
print(thisdict) //{'brand': 'Ford', 'model': 'Mustang', 'year': 2023, 'colors': 'red'}

thisdict.pop("model") // thisdict안의 key가 "model"인 부분을 다 지움(Value도)
print(thisdict) //{'brand': 'Ford', 'year': 2023}

del thisdict["brand"]  //thisdict안의 key가 "brand"인 부분을 다 지움(Value도)
print(thisdict) //{'model': 'Mustang', 'year': 2023}

thisdict.clear()  //thisdict안의 내용을 다 지움., thisdict자체는 남아있음.
print(thisdict) // {}

del thisdict //thisdict라는 변수 자체를 지움
print(thisdict) // 오류

  • for x in 변수명 :

x라는 변수는 a,i 등 아무거나 바꿔줘도 무방하다
단, 뒤에 나오는 변수명은 값을 가져올 것에서 사용해야 함

)
thisdict ={
    "brand" : "Ford", 
    "model" : "Mustang",
    "year" : 2023
}
for x in thisdict :
    print(x) // Key값들 출력

for i in thisdict:
    print(thisdict[i]) //Value값들 출력

for a in thisdict.values():
    print(a) //Value값들 출력

for a in thisdict.keys():
    print(a) //Key값들 출력

for x, y in thisdict.items():
    print(x, y)//Key, Value 모두 출력

  • 리스트 copy()
1)
thislist=["apple","banana","cherry"] //thislist라는 list 생성

mylist=thislist.copy() //mylist에 thislist를 copy함
ulist=thislist[:] //ulist에 thislist[:] 복사, copy()와 동일한 기능
print(mylist)  //["apple","banana","cherry"]
print(ulist) //["apple","banana","cherry"]2)

thisdict ={
    "brand" : "Ford", 
    "model" : "Mustang",
    "year" : 2023
}

print("--> 복사 2")
udict = thisdict              //복사 후에
thisdict["brand"]="kia"      //값을 바꾸었지만
print(thisdict) //{'brand': 'kia', 'model': 'Mustang', 'year': 2023}	          
print(udict) //{'brand': 'kia', 'model': 'Mustang', 'year': 2023}  
//출력 내용은 같음
//참조 성격을 가지기 때문


print("--> 복사 2")
udict = thisdict.copy()	//copy()로 복사 후
thisdict["brand"]="kia"	//값을 바꿈
print(thisdict) //{'brand': 'kia', 'model': 'Mustang', 'year': 2023}
print(udict) //{'brand': 'Ford', 'model': 'Mustang', 'year': 2023}

copy()를 쓰면 Key의 Value값은 새로운 메모리에 값을 저장하여 독립되었다고 볼 수 있다.(얕은 복사), 얕은 복사의 경우 dictionary에 다른 컨테이너 객체가 포함되어 있으면,
다시 참조만 되고 최종적인 값은 복제되지 않는다. 다른 컨테이너 객체 예) list, turple,set)

따라서 중첩된 데이터까지 완전하게 독립된 복사를 원한다면 deepcopy()함수를 써야 한다. (깊은 복사)

  • dictionary 안의 Value가 dictionary형일 때
1)
myfamily ={
    "child1" : {
        "name" : "kim",
        "year" :1990

    },
    "child2" : {
        "name" : "park",
        "year" :2001

    },
    "child3" : {
        "name" : "lee",
        "year" :2010
    }
}
print(myfamily) 
// {'child1': {'name': 'kim', 'year': 1990}, 'child2': {'name': 'park', 'year': 2001}, 'child3': {'name': 'lee', 'year': 2010}}2)
child1 = {
        "name" : "kim",
        "year" :1990
    }
child2 = {
        "name" : "park",
        "year" :2001
    }
child3 = {
        "name" : "lee",
        "year" :2010
    }

myfamily = {
        "child1" : child1,
        "child2" : child2,
        "child3" : child3,
    }

print(myfamily)
print(myfamily["child2"]["name"])
//myfamily의 Key인 "child2"의 Key인 "name"의 Value값 park 출력

예1,2의 myfamily는 서로 같다.

  • jupyter 사용

https://jupyter.org/try-jupyter/retro/notebooks/?path=Untitled.ipynb
링크로 이동


  • matplotlib ★
)

`from matplotlib import pyplot as plt` 
// 모듈을 다운 받는데 이를 부르는 말로 plt라 하겠다.
//pyplot을 사용하기 위해선 적어야 함.

plt.plot(['seoul','paris','london'],[50,20,36])    //그래프1의 x축 ,y축 값을 주기
plt.plot([2,5,6],[7,3,1])                          //그래프2의 x축 ,y축 값을 주기
plt.xlabel('City')                                 // x축 이름 지정
plt.ylabel('Population')                           //y축 이름 지정
plt.title('How many people in City')               // 그래프 제목 지정
plt.legend(['Mouse','Cat'])     //그래프가 여러개 일 때 그래프1, 그래프2 이름 지정
plt.bar(x,y,width=0.5,color="blue")               //막대형 그래프, 막대 너비,색 지정
plt.show()                                        // 그래프 나타내기
1)from matplotlib import pyplot as plt 
예2)import matplotlib.pyploy as plt 
//1),2)는 동일한 기능을 한다.
//matplotlib를 import하여 plt라는 변수로 사용한다는 내용이다.

plt.scatter(x축,y축)  // 점 그래프
plt.plot(x축,y축)     // 선 그래프

  • python에서 matpltlib가 작동 안할 때

Terminal 창에 "pip install matplotlib" 를 쳐서 다운받기
만약 circular import 오류가 난다면 파일 이름을 확인해 볼것.
'matplotlib.py'일 때 circular import 오류가 나왔음.
한글이름인 경우에도 오류가 날 수 있으니 변경할 것.


  • 누적 ★
)
numbers=[1,2,3,4,5,6]            //numbers라는 list 선언
sum=0                            //sum 변수를 선언해줘야 함
for value in numbers:  	
	sum=sum+value	             //sum0에서 시작해서 1,2..6까지 누적함
	#sum+=value	                //이렇게 적어도 같은 값이 나온다
	print(sum)

  • while문에서 else가 필요없는 경우 ★
)

while True:
  x=input("신호등 색상을 입력하세요 :")
  if x == 'blue':
    print('직진하세요')
    break		       //x가 blue일 때만 break, while문을 빠져나간다.
  else:                //따라서 굳이 else continue를 안해줘도 동일한 작동을 한다. 
    continue   

  • python 파일 열고 닫기 ★
1)
f1=open("score.txt",'w')   //score.txt라는 파일을 쓰기모드로 열고 이를 f1변수에 넣는다.
print("국어 : 100",file=f1) //f1에 "국어 : 100"의 내용을 넣는다
f1.write("english : 100")  //f1에 "english : 100"의 내용을 넣는다. 
						   //print와 달리 .write는 줄바꿈이 자동으로 되지 않는다.
f1.close()                 // 파일을 닫는다.2)
f2=open("score.txt",'a',encoding="utf-8") //만들어진 score.txt파일을 add모드로 연다.3)
f1=open("score.txt",'r')     //score.txt 파일을 읽기 모드로 연다
print(f1.read())             //f1파일을 모두 읽고 사용자가 볼 수 있게 출력하게 한다.
print(f1.readline())         //f1파일의 한줄을 읽고 출력, 공백들도 모두 포함되어 출력됨
print(f1.readline(), end="") //한줄을 출력 내용이 끝날때까지 출력됨(공백x)
f1.close()4)
f1=open("demotxt1.txt",'r')
while True:
    line=f1.readline()           //f1의 내용을 읽어라
    if not line:                 //f1의 내용이 없으면 while문 종료
        break
    print(line, end="")
f1.close()

  • (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 에러가 날 때
)
f1=open("C:\Users\a11\Desktop\서문.txt",'r',encoding="utf-8")

예)처럼 절대경로를 주고 파일을 열려고 할 때 문제가 발생했다.
\가 이스케이프 문자기 때문에 경로를 유니코드로 인식했다는 것이다.

따라서 두가지 방법 중 하나를 사용하여 해결한다.

  1. \가 들어가는 모든 곳에 \\ 두번씩 쓰거나
  2. '경로'앞에 r을 붙인다. (r을 붙이면 경로자체를 문자열로 인식하게 한다.)
)
1. f1=open("C:\\Users\\a11\\Desktop\\서문.txt",'r',encoding="utf-8")
2. f1=open(r"C:\Users\a11\Desktop\서문.txt",'r',encoding="utf-8")

  • 파일을 열 때 "encoding="utf-8" 을 넣어주는 이유 ★
)
f1=open("C:\\Users\\a11\\Desktop\\서문.txt",'r',encoding="utf-8")

파일을 읽어들일 때 인코딩 방식에 따라 다른 문자열로 읽힐 수 있다.
따라서 "encoding="utf-8"으로 지정해주면 인코딩 방식을 utf-8로 정한 것이다.
utf-8은 한글 깨짐 방지를 위해서 사용된다.
만약 이를 적지 않을 경우 시스템 디폴드 인코딩 방식을 사용한다.


  • with open() : 사용 ★
)
with open('demotxt1.txt','r') as f: // 'with open() as 변수 :' 의 형식
    text=f.read()   				// with문 들여쓰기 필요
    print(text)     				// with문 들여쓰기 필요, close() 불필요

with open() as 변수 :을 사용하면 close()단계를 생략해도 된다
with 블록이 끝나면 자동으로 close를 해준다.


  • 숫자, 및 문자 순서대로 정렬 .sort()
    역순으로 출력(문자그대로 역순으로만 출력함, sort로 정렬되어 있는 상태에서 reverse를 할 경우 내림차순으로 보이게 된다).reverse()
)
x=[7,4,3,2,6,5,1]
print(x)  // [7, 4, 3, 2, 6, 5, 1]
x.sort()  // 순서대로 정렬
print(x)  //  [1, 2, 3, 4, 5, 6, 7]
x.reverse()// 역순 정렬
print(x)  //  [7, 6, 5, 4, 3, 2, 1]

  • 배열의 초기화 ★
)

score=[0 for x in range(5)]     //배열의 내용을 전부 0으로 초기화 한다. 5번 반복한다.
print(score)  // [0, 0, 0, 0, 0]
 
score=[[2 for _ in range(4)] for _ in range(5)] 
print(score)  // [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]
//배열의 내용이 전부 2이면서 4번 반복한 배열이 있다. 이를 5번 반복하여 score에 넣는다.
// '_''x'와 같이 어떤 변수를 의미하는 것이다. 문자 자체에 의미가 있지는 않다.

기본형 예시
a=[0 for x in range(3)]  // 배열 a는 03번 반복되는 배열이다. a=[0,0,0]

  • numpy 사용

파이썬에서 numpy를 사용하기 위해선 설치가 필요하다 (https://numpy.org/install/)
혹은 https://colab.research.google.com/drive/1Ap1CrcxWuKuls2F5I1icV_JqC6dpqtoS#scrollTo=0wgJdmNAve_3 여기서 따로 설치 없이 사용가능하다.

)

import numpy as np 			// numpy 라이브러리를 불러와서 별칭으로 np지정
				
x = dir(np)    				//numpy가 가지고 있는 속성과 함수를 리스트로 저장
print(len(x))  				//610
print(x[540:550])
// ['square', 'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes']
 
# 1차원 배열 정의
x=np.array([1,2,3])
print(x.shape)     //(3,)       #배열의 모양을 출력
print(x.ndim)      //1           # x배열의 차원 출력

# 2차원 배열 정의
y=np.array([
                [1,2,3],
                [4,5,6]
])
print(y)
//
[[1 2 3]
 [4 5 6]]
print(y.shape) //(2, 3)
print(y.ndim)  //2

# 2차원 배열의 합과 차
b=np.array([ 
              [1,2,3],
              [4,5,6]
            ])

c=y+b
d=y-b

print(c)
//
[[ 2  4  6]
 [ 8 10 12]]

print(d)
//
[[0 0 0]
 [0 0 0]]


  • csv 파일 python으로 가져오기 ★
)
import csv   //csv를 import해준다
with open(r"C:\web\day28\people.CSV",'r',encoding='utf-8') as f: //csv파일을 연다.
    reader=csv.DictReader(f) 				 //csv.DictReader(f)를 변수에 넣어준다.

csv.DictReader() 는 dict형태로 값을 저장한다.

예)
num    male   female
 4      2       2
 5      2       3

위의 값을 가진 csv파일을 불러온다고 했을 때
{'num':'4','male':'2','femal':'2'} //이처럼 dict형태로 값을 저장한다.

a=[[],[],[],[],[]]
i=0
j=0
    for row in reader:
        a[i].append(row)
        j=j+1
        if(j%15==0):
            i=i+1

따라서 위의 경우 실질적으로 a[0]~a[5]까지만 채워지지만 a[0]에서 a[1]로 넘어가기 위해서 15번의 값이 지나야 하므로 각 a[i]에는 15개씩의 값이 있다고 생각할 수 있다.

위의 예에서 a[0][0]의 값은 {'num':'4','male':'2','femal':'2'}이 출력되고
위의 예에서 a[0][1]의 값은 {'num':'5','male':'2','femal':'3'}이 출력된다.

정리. a[0][0]~a[15] a[1][0]~a[1][15] ... a[5][15] 인 dict형 a가 생긴 것이다.
따라서 이 a값중 'num'에 해당하는 값만 지정하고 싶으면
a[0][0]['num'] 으로 해주면 되고 이 경우 4가 출력 된다.


  • python에서 함수 정의 ★
def 함수명() :      //함수 정의
     실행코드

함수명()           //함수 실행

예1)
def greet(name,age):
    print(name,"Hello",age)

greet("홍길동",22) //홍길동 Hello 22 출력

예2)
def cal_area(radius):
    area = 3.14 *radius **2
    return area

print(cal_area(4.0)) //50.24 출력

예3) 1~10까지 합을 보여주는 함수

def get_sum(x,y):
    sum=0
    for i in range(x,y+1):  //range 적어주는 것 잊지 말기
        sum =i+sum
    return sum             //return의 위치 중요, for문 밖에서 return해줘야 한다.

print(get_sum(1,10))      //55출력
        

  • 함수 안의 변수 헷갈리는 부분 ★
)

def circle(radius):                    //함수를 정의할 때 변수 radius라고 사용
    result = 3.14*radius**2            //함수 내용중에 radius가 사용 되어야 한다.
    return result                      //어떤 변수이름이든 상관 없으나 함수정의식()안과 함수정의내용에서
    								   //사용되는 변수이름이 같아야 한다.

r=float(input("반지름을 입력하세요 :"))  
print(circle(r))                         //정의된 함수에 넣는 값은 radius가 아니어도 된다.                                      
                                         //r처럼 임의의 변수로 넣어도 무방하다.

  • global 전역 변수 생성
)
def cal_area(radius):
    global area                  //def 함수에서 선언되는 변수는 원래는 지역변수 이지만
    area= 3.14 * radius ** 2     //global area처럼 앞에 global을 적어주면 전역변수처럼 인식된다.
    return

r = float(input("원의 반지름 입력 :"))
cal_area(r)
print(area)                       //따라서 def 함수 밖에 있는 부분에서도 area가 인식된다.

  • python함수 def( *인자):
예1)

def myF(name,age,*hobby):   //인자 이름앞에 *를 주면 ()튜플형태로 받는다, 
                            //여러 값을 받을 필요가 있을 때 사용한다.
    print("이름은",name,"나이는",age,"취미는",hobby)

myF("emily",20)              //이름은 emily 나이는 20 취미는 () 출력
myF("emily",20,'ski',"낚시") //이름은 emily 나이는 20 취미는 ('ski', '낚시') 출력

예2)
def add_num(*args):	        //*인자의 형태로 값을 받을 때, 여러 값 받을 수 있음.
    result = 0
    for i in args:
        result +=i
    return result
    
print(add_num(1,2,3))               //6출력
print(add_num(1,2,3,4,5,6,7,8,9))  //45출력

  • python함수 def( 기본값=):
)
def greet(name,msg="금요일입니다."):
    print("Hello"+name+","+ msg)

greet("김철수")          //Hello김철수,금요일입니다. 두번째 값이 없을 때 인자msg의 기본값 "금요일입니다"출력
greet("김철수","Today")  //Hello김철수,Today. 두번째 값이 입력되어서 "Today"출력

  • 튜플() tuple 형식

리스트와 매우 흡사하다.
단, 내용이 변경되지 않는다.
( )로 사용된다. (list는 [], 배열은 {})
튜플이 1개의 값만 갖는다면 값 뒤에 콤마(,)를 삽입해야 하고 () 는 생략 가능하다.
리스트처럼 슬라이싱, 길이구하기 등 기본적인 것은 리스트와 동일하다
튜플은 여러개의 변수에 여러개의 값을 한 문장으로 할당할 수 있다.

#튜플의 초기화)
t1=()
t2 =(1,)
t3=(1,2,3)
t4=1,2,3
y5=('a','b',("ab","bc"))
t3[1]=22          //에러 출력된다. 왜냐면 tuple은 값을 변경할 수 없기 때문이다.

#튜플은 변수의 값 교환이 x,y=y,x로 가능하다
x=10
y=20
x,y=y,x
print(x) #20
print(y) #10

#튜플은 데이터가 변경되지 않는 구조이기 때문에 튜플의 정렬(.sort())은 불가하다, 1.정렬에 대한 규칙을 만들어서 사용하거나
def sort_num(x):
    return x
numbers=(10,3,11,9,8)
sorted_num=tuple(sorted(numbers,key=sort_num))
print(sorted_num)

2-1. labmda표현식을 이용한다.
numbers=(10,3,11,9,8)
sorted_num2=tuple(sorted(numbers,key=lambda x:x))
print(sorted_num2)

2-2.
int 와 string이 섞여있을 때 가능하다.
numbers=(10,'3',11,9,'8')
sorted_num3=sorted(numbers,key=lambda x:int(x))
print(sorted_num3)

  • turtle
)
import turtle
t = turtle.Turtle()   //t라는 변수에 Turtle명령어 저장
t.shape('turtle')     //화살표 모양을 거북이로

t.up()                //그림을 그릴 때 펜을 올렸다고 생각하면 됨
t.goto(200,50)        //좌표 (200,50)으로 이동, 들고 이동하면 이동할 때 안그려짐
t.down()		      //다시 펜을 내려줌

  • csv자료를 이용한 그래프 만들기. 헷갈리는 부분 정리 ★
1)
import csv

a=[[],[],[],[],[]]
i=j=0
with open(f"C:\web\day29\people.csv",'r',encoding='utf-8') as f:  //변수 이름을 'f'등 으로 지정할 것
    reader=csv.DictReader(f)   //f에서 값을 가져온다
    for row in reader:      //i,j가 아닌 제3의 변수 row를 써야 하고 
                            //csv파일을 DictReader로 읽어온 reader에서 값을 가져와야 함.
        a[i].append(row)    //append()의 코드 원형 다시 인지할 것
        j=j+1	            //위 코드는 a라는 배열에 dict형으로 읽히는 row를 하나씩 넣어주는 것이다.
        if j%15==0:
            i=i+1

2)
sump=summ=0
avgp=avgm=[]  //이렇게 정의해서 오류가 났음. avgm하나만 리스트형으로 선언한 것.
	          //avgp,avgm=[],[] 이렇게 해줘야 함.

for j in range(15):
    for i in range(5):
        sump+=int(a[i][j]['num'])
        summ+=int(a[i][j]['nummale'])
    avgp.append(sump/5)       #이부분을 계속 헷갈렸음
    avgm.append(summ/5)
  1. 해석

얻어야 하는 값이 시간별(8시~22시) 평균 유동인구 수이다.
따라서 평균 값이 [1,2,3....,15]처럼 값이 15개인 리스트형으로 나와야 한다.
그렇다면 a[0][0]['num'] 다음 더해줘야 하는 값은
a[0][1]['num']이 아니라 a[1][0]['num']이 된다.
왜냐면 a[0][1]['num']는 월요일, 9시를 의미하고,
a[1][0]['num']는 화요일 8시를 의미하기 때문이다.

따라서 for j in range(15)안에 for i in range(5)를 해줘야 한다. (순서 주의)

sump,summ은 모두 하나의 값으로 나온다.
왜냐면 월요일 8시 인구+화요일 8시 인구...+금요일 8시 인구는 하나의 값이기 때문이다.
그렇다면 이 값들을 앞서 얘기한 것처럼 [1,2,3....,15]처럼 값이 15개인 리스트 형식으로 정리하여 평균값을 구해야 한다.

즉, avgp,avgm=[],[] 리스트 형으로 선언을 한 후
각 시간대별 합계/5의 값을 15번씩 추가해주면 된다.

결과적으로 avgp,avgm에는 각 시간대별 평균 인구수가 리스트형(값 15개)으로 정의된다.


  • python data type

파이썬에는 6개의 타입이 있다.
1. Numberic type : int,float,complex(복소수)
2. Sequence type : 문자열, 리스트 (list), 튜플(tuple)
3. Mapping type :dict(딕셔너리)
4. Set type : set(집합)
5. Boolean type : bool(불리언)
6. Binary type : bytes, bytearray, memoryview

bin =0b10 (2진수)
oct =0o10 (8진수)
dec =10 (10진수)
hex =0x10 (16진수)


  • 수학 관련
1)(//) 제곱(**)

y=100
y//=y  #1(100//100)2)
import math
print(math.ceil(5.1)) #올림해서 6
print(math.floor(3.874)) #내림해서 3
print(abs(-10)) #절대값3)
print(math.pow(x,y)) #x의 y승
print(math.pow(7,2)) #7의 2승
print(math.sqrt(9)) #제곱근4)
import random #random을 import해주기
num = random.random() #랜덤으로 생성
print("random import 후",num)
num1=random.randint(1,500) #범위내의 정수 생성
print("1~500 사이",num1)



  • 문자열 관련
)
str="Life is too short, You need python"
print(str[2:34:3]) #fit o,ondyo 출력 // 시작:종료:간격


count_str="adgveaeaagegeg"
print(count_str.count('e')) #4 'e'의 갯수 출력

str1="python"
print(".".join(str1))  #p.y.t.h.o.n
print("-".join(str1))  #p-y-t-h-o-n

a="          hi           "
print(a.lstrip()+"*") #왼쪽 공백 지우기 
print(a.rstrip()+"*")#오른쪽 공백 지우기
print(a.strip()+"*") #좌우 공백 지우기

  • 변수명 keyword
)
import keyword
print(keyword.kwlist)
#['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 이것들은 변수명으로 설정하면 안된다.

  • end= ""
)
for x in range(int(len(reversed_word))):
    print("[{:^10}]".format(reversed_word[x]),end="") 
    #[]안에 10칸중 가운데 정렬된 부분에
    # reversed_word의[x]값을 넣겠다.
    if (x+1)%5==0: #5개씩 쓰고 띄어쓰기 하겠다
        print("\n")

#출력 결과
[  False   ][   None   ][   True   ][   and    ][    as    ]

[  assert  ][  async   ][  await   ][  break   ][  class   ]

[ continue ][   def    ][   del    ][   elif   ][   else   ]

[  except  ][ finally  ][   for    ][   from   ][  global  ]

[    if    ][  import  ][    in    ][    is    ][  lambda  ]

[ nonlocal ][   not    ][    or    ][   pass   ][  raise   ]

[  return  ][   try    ][  while   ][   with   ][  yield   ]

end=""을 함으로써 5개씩 옆으로 붙어서 출력됨


  • dictionary에서 .get()함수
)
a={'name':'Smith','phone':'01012345678','birth':'1990'}

print(a["location"]) #없는 key를 물어보면 오류
print(a.get("location")) #없는 key를 물어보면 none출력  None
print(a.get("location",'not found')) #2번째 인자로 디폴트값을 줄 수 있다. not found

  • in 을 사용한 존재 여부 확인 ★
)
a={'name':'pey','phone':'01012345678','birth':'1990'}
print("name" in a)  #True 
print("pey" in a)  #False  dictionary형일 때 in함수는 key값만 확인 가능하다.

  • append()로 추가, extend()로 추가
)

a=[1,2,3,4,5]
a.append(6)
print(a)       #[1, 2, 3, 4, 5, 6] 출력
a.append([7,8,9,10]) #추가
print(a)       #[1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] 출력
b=[1,2,3,4,5]
b.extend([7,8,9,10]) #확장
print(b)       #[1, 2, 3, 4, 5, 7, 8, 9, 10]출력

  • 집합 set ★

집합은 set 키워드를 사용하며 중괄호{} 사이에 정의된다.
집합의 각 요소는 고유하고 불변해야 하며 중복요소를 가지면 안된다
집합은 변경가능하므로 생성 후에 수정이 가능하다
set은 정렬되지 않는 항목 또는 데이터 유형의 모음으로 저장된 요소의 순서가 고정되어 있지 않아서 인덱스를 이용한 접근이 불가능하다
int,float,tuple유형의 요소를 포함할 수 있지만 가변요소(리시트, 딕셔너리, 집합)는 집합의 요소가 될 수 없습니다.
교집합, 합집합, 차집합을 구하는데 용이하다
set의 기본형태 : 리스트형태나 문자열 형태로 만들 수 있음

)

s1=set([1,2,3,1,2,3])
s2=set("Hello")
print(s1)  # {1, 2, 3} 자동으로 중복제거 되어 출력됨
print(s2)  # {'e', 'H', 'o', 'l'} 자동으로 중복제거 되어 출력됨

#집합은 인덱싱을 할 수 없다. 하지만 리스트형으로 변환하면 사용가능하다.
list_s1=list(s1)
list_s2=list(s2)
print(list_s1)
print(list_s2)
print(list_s1[1])  2
print(list_s2[1])  o

#교집합 & (set1).intersection(set2)
s1=set([1,2,3,4,5,6])
s2=set([4,5,6,7,8,9])

print(s1 & s2) # {4, 5, 6} 출력
print(s1.intersection(s2)) # {4, 5, 6} 출력

#합집합 |   (set1).union(set2)
s1=set([1,2,3,4,5,6])
s2=set([4,5,6,7,8,9]) 
print(s1|s2) #{1, 2, 3, 4, 5, 6, 7, 8, 9}
print(s1.union(s2))  #{1, 2, 3, 4, 5, 6, 7, 8, 9}

#차집합 -  (set1).difference(set2)
s1=set([1,2,3,4,5,6])
s2=set([4,5,6,7,8,9])
print(s1-s2) # {1, 2, 3}
print(s1.difference(s2)) # {1, 2, 3}


  • startswith()
)
def playAgain():
    print("게임을 계속 하시겠습니까 (yes or no)")
    return input().lower().startswith('y') #true or false로 나옴

시작 단어가 y로 시작하면 TRUE가 나옴


  • turtle 이미지 처리
)
import turtle           #그래픽처리
import numpy as np      #행렬데이터를 처리하기 위한 모듈

myImg=np.array(
    [
        [0,0,0,0,0,0,0,0],\
        [0,1,1,1,0,0,0,0],\
        [1,1,1,1,1,0,0,0],\
        [1,1,1,1,1,0,0,0],\
        [0,1,1,1,0,0,0,0],\
        [0,0,0,0,0,0,0,0],\
        [0,0,0,0,0,0,0,0],
    ]
)

#사각형을 그리고 색상을 흰색 또는 오렌지 색으로 칠하기
def putPixel(x,y,psize,pcol):
    turtle.penup()
    turtle.goto(x*psize,(-1)*y*psize)
    turtle.pendown()
    turtle.begin_fill()
    turtle.fillcolor(pcol)
    turtle.setheading(45)
    turtle.circle(psize/2,steps=4)
    turtle.end_fill()

pixelsize=20
for j in range(0,8):
    for i in range(0,8):
        if (myImg[j][i]>0):
            putPixel(i,j,pixelsize,'orange')
        else :
            putPixel(i,j,pixelsize,'white')

  • 헷갈렸던 함수의 원형들★

np.array([]) //행렬데이터를 처리하기 위해 사용
turtle.penup()
turtle.pendown()
turtle.fillcolor()
turtle.setheading() //각도 조정
turtle.circle(크기, steps=각의 갯수) //steps=에 넣는 수로 n각형을 만들 수 있다.


  • 집합(set)에서 add(), remove(),pop(),clear(),discard()
)
months=set(["January","Fe","Mar","Apr","May","June"])
print("\n원래값")
print(months)

months.add("July")
print('add후에',months)  #"July"가 추가되긴 하지만 집합형이기때문에 각각의 순서가 출력마다 바뀜

months.remove("January") #"January"를 특정해서 제거 했기 때문에 알맞게 제거됨.
						#("Jan")이라고 잘못된 값을 주었을 때 오류가 출력됨

months.pop()  #할 때마다 다른 내용이 제거됨

months.clear() # set()이 출력됨 , 내용을 비워줌

months.discard("January") #"January"를 제거함.
						#("Jan")이라고 잘못된 값을 주었을 때 "January"가 사라지지는 않지만 오류는 안남.

  • 집합 합집합 |,set1.union(set2)
)  합집합 |, set1.union(set2)
days1={"monday","Tuesday",'We',"Th","Sun"}
days2={"Fri","Sat",'Sun'}

print('days1과 day2를 합치면',days1|days2)
#{'Fri', 'Sun', 'monday', 'Tuesday', 'We', 'Sat', 'Th'} 출력
#"Sun"이 중복되지만 겹쳤을 때 한번만 나옴
print('days1과 day2를 합치면',days1.union(days2))
#{'Fri', 'Sun', 'monday', 'Tuesday', 'We', 'Sat', 'Th'} 출력
#"Sun"이 중복되지만 겹쳤을 때 한번만 나옴

  • 집합 교집합 &,set1.intersection(set2)
) 교집합 &, set1.intersection(set2)
days1={"monday","Tuesday",'We',"Th","Sun"}
days2={"monday","Tuesday",'We',"abc"}

print('days1과 day2의 겹치는 요소들만',days1&days2)
#{'monday', 'We', 'Tuesday'} 겹치는 요소들만 출력됨
print(days1.intersection(days2))
#{'monday', 'We', 'Tuesday'} 겹치는 요소들만 출력됨

  • 집합 교집합하여 할당 intersection_update()
)
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway","bob"}
c = {"fuson", "gaurav", "castle"}

a.intersection_update(b,c) #a에 a,b,c의 교집합 부분을 저장한다.

print('intersection_update후 a',a) # {'castle'}출력 a에 a,b,c의 교집합 부분을 저장
print('intersection_update후 b',b) #그대로 출력
print('intersection_update후 c',c) # 그대로 출력

  • 집합 빼기 차집합-, set1.difference(set2)
)
days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}
days2 = {"Monday", "Tuesday", "Sunday"}
print(days1-days2) #{'Thursday', 'Wednesday'} 출력 day1중 day2에 있는 내용만 제거해서 출력
print(days1.difference(days2)) #{'Thursday', 'Wednesday'}출력 day1중 day2에 있는 내용만 제거해서 출력

  • 집합 여집합 ^,set1.symmetric_difference(set2)
)
a={1,2,3,4,5,6}
b={1,2,9,8,10}
c=a^b
print(c) #{3, 4, 5, 6, 8, 9, 10} a,b에서 겹치는 부분을 제외한 나머지 부분(여집합) 출력
d=a.symmetric_difference(b)
print(d) #{3, 4, 5, 6, 8, 9, 10} a,b에서 겹치는 부분을 제외한 나머지 부분(여집합) 출력

  • 집합 비교연산자
)
days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
days2 = {"Monday", "Tuesday"}
days3 = {"Monday", "Tuesday", "Friday"}

print('days1>days2:',days1>days2) # True 출력
print('days1.issuperset(days2):',days1.issuperset(days2)) # True 출력 day1이 day2의 상위 집합인가?
														#(=day2가 day1의 부분집합인가)
print('days1.issubset(days2):',days1.issubset(days2)) # False 출력 day1이 day2의 부분집합인가
print('days2.issubset(days1):',days2.issubset(days1)) # True 출력 day2가 day1의 부분집합인가
print('days1<days2:',days1<days2) # False 출력
print('days1==days2:',days1==days2) # False 출력

파이썬에서는 비교 연산자 <,>,<=,>= 등을 set()과 함께 사용할 수 있다.
이를 통해 집합이 서브셋인지 슈퍼셋인지, 또는 다른 세트와 동일한지를 확인할 수 있다.
집합 내부에 있는 항목에 따라 True 또는 False를 반환한다.


  • 집합에 추가하기
)
set1=set([1,2,4,"John",'cs'])
set1.update(["Apple","Mango","Grapes"]) 
print(set1) #{'cs', 1, 2, 4, 'Apple', 'John', 'Mango', 'Grapes'} 출력 (둘의 내용을 합친 값)

  • 집합 비교 set1.isdisjoint(set2) 뜻 : set1,set2에서 겹치는 요소가 없는가?
)
#set이 같은지 다른지 비교
a={1,2,3,4}
print(a=={1,2,3,4}) #True a와 같음
print(a=={1,2,4,3}) #True 순서가 달라보여도 집합이라 a와 같음

#set에 겹치는 요소가 있는지 없는지 확인하기
print(a.isdisjoint({5,6,7,8})) #True 집합 a와 겹치는게 없는가?라고 물었을 때 True임
print(a.isdisjoint({3,4,5,8})) #False 집합 a와 겹치는게 없는가?라고 물었을 때 False임 (3,4)가 겹침

  • 집합 상위집합(superset),부분집합(subset) ★
)
set1 = set(["Peter","James","Camroon","Ricky","Donald"])
set2 = set(["Camroon","Washington","Peter"])
set3 = set(["Peter"])

issubset=set1>=set2
print(issubset)  #False 출력 set1가 set2보다 내용은 더 많다.	
				#단,set2의 모든 내용을 다 가지고 있지 않기 때문에 상위집합이 아니다.
issuperset=set1<=set2
print(issubset) #False 출력 set1이 set2의 내용중에 있는 값으로만 이루어지지 않기 때문에 부분집합이 아니다.

  • 이미지 불러오기
)
#외부 모듈 읽어오기
import numpy as np
import matplotlib.pyplot as plt
import PIL.Image as pilimg   #이미지 불러오는 모듈

#이미지 파일 불러오는 형식
im1=pilimg.open(r'C:\Users\a11\Downloads\jeju_summer.jpg') 
im2=pilimg.open(r'C:\Users\a11\Downloads\baby1.jpg')
im3=pilimg.open(r'C:\Users\a11\Downloads\baby2.jpg')

  • 공공데이터 이용

data.go.kr 공공데이터 사이트
data.kma.go.kr 기상정보 사이트 -> 기후통계 분석텝 csv,excel자료등 선택하여 다운가능
네이버 데이터랩-쇼핑인사이트-조회결과 다운로드


  • 아나콘다 이용

https://www.anaconda.com/products/distribution/start-coding-immediately
아나콘다 다운로드 설치시 add path체크
아나콘다 네비게이터 - 주피터 설치 - new, ipykernel
vscode같은 프로그램 사용가능


  • 공공데이터 분석 ★
1)
import csv
f=open(r'C:\Users\a11\Downloads\ta_20230215142047.csv')
file=csv.reader(f)   #csv파일은 콤마로 구분된다.
next(file)     #행을 넘겨주는 역할을 함 (헤더를 넘기고 값만 받을 때 사용)

max_temp=[]
for row in file:
    if row[-1] !='':    #오래된 데이터라 값이 없는 부분도 있을 수 있어서 넣음
        max_temp.append(float(row[-1])) #소숫점도 있기 때문에 float형으로 받음

plt.plot(max_temp,'g--')  #녹색 점선의 그래프 출력 

plt.hist(max_temp,bins=100) #막대모양의 그래프를 출력하는데 총100개의 막대로만 표현하라는 뜻

plt.show()2)
for row in file:
    if row[-1] !='' and row[0].split('-')[1]=='10':  #전체 자료에서 10월에 해당하는 자료만 가져오기.
        max_temp.append(float(row[-1]))

plt.hist(max_temp,bins=100,color="red")




  • 클래스 ★
1)
class Mycar:    #클래스 선언, 클래스 선언시 변수 첫글자는 대문자로 써야함.
    a=10

n=Mycar()      #n이라는 변수에 Mycar()라는 클래스를 할당
print(n.a)        #10출력2)
class Car:         #클래스 선언할 때는 ()를 안적음 단, 적어도 오류는 안남.
    #속성
    def __init__(self):   #__init__(초기화) 'self'라는 단어를 꼭 적어야 하는건 아님.
        self.name='hyundai'  
        self.color='red'
    #메소드  ,동작등 설정
    def driving(self):
        print('드라이브가자')

mycar=Car()   #클래스를 할당할 때는 ()를 적어야 함
print(mycar.name)
print(mycar.color)
mycar.driving()  #메소드를 출력, 함수기 때문에 () 적을것

  • 클래스 저장 속성
)
class Calculator:
    def __init__(self):
        self.result=0      #전역변수(global)로 선언하는 것과 같은 역할을 한다.
    def add(self,num):
        self.result += num
        return self.result

cal1=Calculator()
cal2=Calculator()
print(cal1.add(3))  #result=3으로 바꾸어 기억함
print(cal1.add(4))  #result=0이 아니라 3으로 기억한 상태에서 4를 더하는 거라 7이 출력됨
print(cal2.add(3))  #result가 저장되어 있는건 cal1이기 때문에 cal2를 부르면 다시 0부터 시작함


  • 클래스의 속성을 나중에 지정하는 방법
)
class Car:                 #클래스를 선언할 때 model,year,color등의 속성은 선언 안했음
    def drive(self):
        self.speed=60

myCar=Car()
myCar.model="e-class"   #클래스의 속성 선언
myCar.year=2017		    #클래스의 속성 선언
myCar.color='blue'		#클래스의 속성 선언
print(myCar.model)		#"e-class" 출력
print(myCar.year)		#2017 출력
print(myCar.color)		#blue 출력

  • 클래스 __init__, __str__
)
class Person:
    def __init__(me,name,age):             #초기화를 해줌
        me.name=name
        me.age=age
    def __str__(self):                     #자신을 부를 때 
        return f"{self.name}({self.age})"

p1=Person('john',30)
print(p1)  #john(30) 출력


__init__  #클래스에서 초기화 해주기 위한 코드
__str__   #인스턴스 자체를 출력할 때 사용되는 코드

  • import 방식
)
from tkinter import * #tkinter 라이브러리의 * 즉,모든 내용을 가져오겠다는 뜻.
import tkinter        #tkinter 라이브러리의 특정한 것을 가져오겠다는 뜻
                      #용량 등의 차이가 있음.

  • module(모듈)

module(모듈)이란 code로 된 라이브러리와 같다. 응용프로그램에서 필요로하는 기능을 모아 놓은 파일이다.
module을 만들려면 파일명.py안에 필요한 코드를 넣으면 된다.
module은 array,dictionary,object를 포함할 수 있다.
module은 class나 변수등을 포함 할 수 있다


  • module import를 Terminal에서 하는 법 ★
  1. python 터미널 창에서 'dir'을 통해 현재 위치 확인.
  2. 'cd 폴더명'을 입력하여 파일이 있는 폴더로 이동
  3. 터미널창에 'python'을 입력
  4. 터미널 창이 '>>>'로 바뀌는지 확인 (다시 돌아가려면 'exit()'입력 )
  5. '>>>'로 된 터미널 창에서 'import 파일이름' 작성

  • module import 하는 법
)
#person.py 파일안에 dictionary형 person1을 만든다.

person1={
    "name":"Smith",
    "age":30,
    "country":"korea"
}

# m2.py라는 다른 파일로 간다.

import person  		#person.py파일을 import해옴 이때 확장자명은 안쓴다.
a=person.person1['name']
print(a)            #Smith 출력

  • import 종류 ★
)

from m3 import sub  #m3라는 파일에서 sub라는 함수만 import해온다
		  		    #함수를 불러올 때 m3.add()사용 => m3.를 붙여야 한다.
from m3 import *    #m3라는 파일에서 모든내용을 import해온다
		            #함수를 불러올 때 add() 사용   => m3.를 생략해도 된다.
import m3		    #m3라는 파일에서 모든내용을 import해온다
from pkg import *   #pkg라는 폴더의 모든내용을 import해온다
					#__init__.py파일에 __all__변수로 import해올 함수를 지정한 경우,
                    #지정한 모든 함수를 불러올 수 있다.


  • 패키지 import할 때 ★
1)
폴더안에 __init__.py 라는 파일을 만든다. 파일안에 내용이 없어도 폴더안의 파일들을 패키지로 인식한다.

 __all__=[
    'mod1',
    'mod2',
    'mod3',
    'mod4'
]
__init__.py 피일에서 위처럼 패키지에서 사용되는 파일들을 초기화 해줄 수 있다
__all__ 로 import해올 함수들을 지정하면 from 파일이름 import * 했을 때 지정한 모든 함수를 불러올 수 있다.2)
pkg폴더안에 '__init__.py','mod1.py','mod2.py','mod3.py','mod4.py'파일들이 있을 때
from pkg import *      #pkg라는 폴더의 모든내용을 import해온다 (__all__로 지정한 모든것)
from pkg.mod3 import * #pkg폴더 안의 mod3내용만 import해온다

  • 패키지에서 __name__
)
print(f'초기화 파일 불러오기 {__name__}') 
#__init__파일안에 이렇게 적어주면 __name__ 부분에 폴더이름이 출력된다.

  • 패키지에서 __all__
# *를 이용하여 import할 때 __init__.py 파일에 __all__이라는 변수를 설정하고,
# import할 수 있는 모듈을 정의해 주어야 한다.
# __all__로 정의하지 않으면 *에 인식되지 않는다.) from pkg import *   
#__init__.py 파일에서 __all__로 가져올 변수를 정하면 이를 *(애스트리크)가 읽어오는 것이다.

  • 패키지

패키지는 특정한 과제 (task)를 수행하기 위한 다양한 기능을 포함하는 컨테이너이다.
패키지를 사용하는 이유:
많은 양의 코드를 하나의 파일에 담는것은 좋지 않다(관리가 어려움)
여러개의 파일에 분리관리한다. 이렇게해서 재사용가능
파이썬에서 (.)도트연산자를 사용해서 패키지에서 모듈을 가져온다
패키지는 계층구조로 되어있고, 모듈은 .py로 되어있다.
__init__.py는 파이썬 3.3버전 이상에서는 적지 않아도 패키지로 인식한다.
하지만 하위버전과의 호환을 위해 넣어준다.
if __name__=="__main__": 을 사용하는 이유 :
다른 프로그래밍 언어에서는 시작하는 파일을 지정할 수 있다. 예)C언어 main()
하지만 파이썬은 시작해주는 곳이 정해져 있지 않다.
그래서 if __name__=="__main__": 을 사용한다. (이곳에서 시작하라는 의미)


  • 클래스 상속 ★
)
class Employee:
    interest=1.02
    def __init__(self,first,last,pay):
        self.first=first
        self.last=last
        self.pay=pay

    def fullname(self):
        return "{} {}".format(self.first,self.last)
    
    def sallay(self):
        self.pay=int(self.pay*self.interest)
        return self.pay

class Developer(Employee): #Developer라는 class를 새로만드는데 Employee라는 class에서 상속을 받아옴
    interest=1.10          
    def __init__(self,first,last,pay,prog_lang): #다 같지만 prog_lang이 추가됨
        super().__init__(first,last,pay)        #Employee가 super가 되기 때문에 같은 부분은 가져옴.
        self.prog_lang=prog_lang  				#Employee에 없는 내용은 새롭게 추가함

print(issubclass(Manager,Developer)) 		#왼쪽이 오른쪽의 상속을 받았는가? True/False로 출력됨

  • datetime모듈 date Time 함수 import ★
1)
from datetime import date  #datetime 모듈 import (date부분 가져옴)

todays_date=date.today()  #todays_date에 date.today()할당
print(todays_date)         #2023-02-21
print(todays_date.month,todays_date.day,todays_date.year) #2 21 2023
print(todays_date.weekday()) #월요일 0, 화요일 1 ... 출력2)
from datetime import date #datetime 모듈 import (date부분 가져옴)

todays_date=date.fromisoformat('2023-03-01') 
print(todays_date) #2023-03-01
print(str(todays_date)) #이것은 date.fromisoformat('2023-03-01')와 동일하다. #2023-03-01
print(todays_date.isoformat()) #2023-03-013)
#날짜 비교가능, 이후날짜는 이전날짜보다 크다.
#날짜 덧셈 및 뺄셈은 datetime.timedalta 객체로 결과를 제공한다.
#날짜를 비교, 더하기/빼기 연산을 시간객체에 사용할 수 있다.

from datetime import date #datetime 모듈 import (date부분 가져옴)

todays_date=date.today()
d1=date(2020,5,14)          #d1변수에 2020년 5월 14일 할당
print(todays_date > d1)    #True
print(todays_date - d1)    #1013 days, 0:00:004)
#시간(시,분,초,microsecond,tzinfo)을 제공한다.

from datetime import time #datetime 모듈 import (time부분 가져옴)

t1=time(14,25,36,18625)
print(t1)      		#14:25:36.018625
t2=time(2,19)
print(t2)   		 #02:19:00
print(t1<t2) 		 #False5)
#datetime.datetime 객체는 날짜와 시간을 datetime객체에 연결한다
#형식 datetime.datetime(년,월,일,시간,분,초,마이크로초,tzinfo)
#datetime.datetime 객체는 딕셔너리의 키로 사용할 수 있다
#date(), time() 함수 제공

from datetime import datetime
dt1 = datetime(1941, 12, 7, 7, 53) 
print(dt1)                         #1941-12-07 07:53:00
print(dt1.date())                 #1941-12-07
print(dt1.time())                 #07:53:006)
#datetime.datetime.now()는 현재의 날짜와 시간

from datetime import datetime

t3=datetime.now()
print(t3.time())                      #11:24:30.610261
print(t3.date())                      #2023-02-21
print(t3.hour,t3.minute)           #11 24
print(str(t3.month)+"-"+str(t3.day)+"-"+str(t3.year))  #2-21-2023

  • map() 함수 ★

map() 함수란 각 요소들에 특정한 함수를 적용시킬 때 쓰는 함수이다.

)
def f(x):
    return x+10     #변수에 10을 더하는 함수 f()

numlist=[1,2,3,4,5]
print(list(map(f,numlist)))  #numlist를 각각 함수 f()에 대입하는 것이다.
		         #[11, 12, 13, 14, 15] 각각의 결과값을 list화해서 출력함.
                 #list를 꼭 해주어야 한다.

  • lambda() 함수 ★
)
def add(n1,n2):
    return n1+n2
print(add(10,20))               #30

add=lambda n1,n2 : n1+n2  #위의 함수식과 같다. 
print(add(10,20))                #30
lambda 매개변수 : 표현식    #함수의 원형2)
map()과 같이 사용가능

numbers=[1,2,3,4,5,6,7,8,9]
square=lambda n : n**2
print(list(map(square,numbers)))  #[1, 4, 9, 16, 25, 36, 49, 64, 81] 출력

  • filter()함수
)
#filter는 이름 그대로 조건에 만족하는 것들만 추출한다.
n=[4,3,2,1]
print(list(filter(lambda x : x>2, n))) #[4,3]  n의 값 중x가2보다 큰거를 추출해서 리스트화해서 출력함

  • reduce() 함수
)
from functools import reduce  #functools의 reduce를 import해주어야 함
n=[4,3,2,1]
print(reduce(lambda x,y :x*y,n))

#reduce함수 실행과정
#1. 처음에는 정상적으로 작동 4*3
#2. 처음 실행결과를 인자로 가져와서 다음 실행 12*2
#3. 2번과정의 반복 24*1
#4. 결과 24 출력

  • 오류 출력 메시지 ★

ArithmeticError : 수의 연산에서 문제가 발생할 때
EOFError : 파일에서 더이상 읽을 데이터가 없을 때
Exception : 가장 상위의 예외 처리
FileExistsError :이미 있는 파일이나 폴더를 생성하려고 할 때
FileNotFoundError : 없는 파일을 오픈하려고 할 때
ImportError : 모듈을 임포트 할 수 없을 때
IndentationError : 코드에서 들여쓰기가 잘못되었을 때
IndexError :잘못된 범위의 인덱스를 사용할 때
KeyError : 잘못된 키를 인덱싱 할 때
ModuleNotFoundError : 불러올 라이브러리 모듈이 없을 때
NameError : 잘못된 식별자 이름을 사용할 때
OSError :운영체제와 관련괸 문제가 발생할 때
SyntexError : 프로그램 문법 오류가 발생할 때
TypeError :데이터형이 잘못되었을 때
ValueError :데이터의 값이 잘못되었을 때
Warning : 심각한 오류는 아니지만 주의가 필요할 때
ZeroDivisionError : 수의 연산에서 0으로 나눌 때

Arithemetic(영어에서 숫자를 말함)
EOF(end of file)
exit(존재하다)
identation(들여쓰기)
index(인덱스)
os(operating system,운영체제, 윈도우,맥os등을 말함)
syntax(문법, 문장등의 의미)
value(값의 의미)
division(나누기)


  • try ~ except(~else)문 형식 ★
)
date=True
while date:      #date의 값이 null이 들어오면 false로 종료
    try:          #try: 프로그램에서 발생가능성이 있는 작업을 실행해 보는 부분
        date=input('월,일을 입력하세요')
        mm,dd=date.split()
        mm,dd=int(mm),int(dd)
    except:      #except : 예외가 발생했을 때 처리하는 코드
        print("잘못된 입력입니다")
    else:          #else : 예외가 발생하지 않았을 때 실행하는 코드
        print('%d 월 %d 일'%(mm,dd))

  • json.loads() ,json.dumps()
1)

import json   #json을 import해준다.
demo='{"name":"Kim","age":30,"city":"Seoul"}' #dictionary처럼 보이지만 str형이다.
print(type(demo))      #<str>
result=json.loads(demo)   #json.loads()  json문자열을 python객체로 변환해줌
print(type(result))    #<dict>
print(result['name'])  #Kim 출력2)
import json
demo ={              #객체형태 변수demo
    "name":"Kim",
    "age":30,
    "city": "Seoul"
}    
print(demo['name']) #Kim
result =json.dumps(demo)  #json.dumps() #python의 객체를 json 문자열로 변환한다.
print(result)  #{"name": "Kim", "age": 30, "city": "Seoul"} 
print(type(result)) # <class 'str'> 출력은 객체로 보였지만 문자열로 바뀐것을 알 수 있다
print(result[:7]) # {"name"  문자열이기 때문에 이 코드가 동작한다.

  • import 파일명 오류 ★
)
AttributeError: partially initialized module 'json' has no attribute 
'loads' (most likely due to a circular import) 

현재 실행시킨 파일 이름이 import한 모듈의 이름과 같을 때 생기는 오류이다.
circular import일 때 보통 파일 이름을 변경하면 해결된다.

  • overriding
1)
class A:
    def disp(self):
        print('This is parent method')

class B(A):  #A를 상속받음
    def disp(self):
        super().disp()  #Aclass의 disp함수 내용을 그대로 적은거라 생각하면 됨
		  #print('This is parent method')를 적은 것임
        print('This is child method')
obj=B()
obj.disp()    #'This is parent method 와 
	    	  #This is child method 출력2)
class Add:
    def result(self,x,y):
        print("Addition",x+y)
class Multi(Add): #Add를 상속받음
    def result(self,x,y):
        super().result(x,y)     #Add class의 result함수 내용을 그대로 가져오는 것.
		          				#이때 x,y라는 인자를 갖기 때문에 넣어줘야 함.
        print("Multiplication",x*y)

m=Multi()              
m.result(10,20)    # Addition 30 과
				   # Multiplication 200 출력


  • __eq__() 함수
)

class Book():
    def __init__(self,title,pages):
        self.title=title
        self.pages=pages
    
    def __eq__(self,other):
        if self.title ==other.title and self.pages==other.pages:
            return True
        return False

book1=Book("Are you My Mother?",72)
book2=Book("Are you My Mother?",72)
print(book1==book2)  #book1과 book2는 내용이 같지만 False가 나온다 (각기 다른 부분을 가리키고 있기 때문)
#이때 __eq__로 이루어진 함수를 적어주면 값이 True로 바뀐다.

  • 패킹과 언패킹 ★
)

#패킹
def pack_it(*args):  
    print(args)
    print(type(args))
#나중에 함수를 호출할 때 몇개의 인자를 받을지 알 수 없다.
#때문에 인자 부분에 *args로 넣는다. 
#이 경우 함수를 호출 할 때 인자의 갯수에 영향을 받지 않는다. 
#결과 값은 튜플 형태로 나온다

x="forest"
y="hill"
z='rose'
pack_it(x,y,z)

#언패킹
def pack_itt(x,y):
    print(x)
    print(y)

args=["forest","rose"]
pack_itt(*args)

  • getattr() setattr()함수
)
class Employee:
    name='David'
    salary=55000
    job='Developer'

p1=Employee()
print('David의 연봉은 ',getattr(p1,'salary'))  #p1에서 salary 속성값을 가져와달라
print('David의 연봉은 ',p1.salary)
setattr(p1,'age',33)  						  #p1에 age속성을 만들고 33의 값을 넣어라
print('David의 나이는', getattr(p1,'age')) 	  #p1에서 age 속성값을 가져와 달라
setattr(p1,'name','Sam')  					  #p1의 name을 Sam으로 바꿔라

  • enumerate() 함수
)
x=('apple','banana','cherry')
y=enumerate(x)  #리스트의 원소에 순서값(인덱스값)을 부여해주는 함수
print(list(y))  # [(0, 'apple'), (1, 'banana'), (2, 'cherry')] 출력

  • sys module ★
)
import sys # sys module을 import하면

sys.exit() #이 함수를 쓸 수 있다.
#운영체제를 돌리는데 필요한 자원을 그만 가져가도록 끝내주는 역할을 한다.
#프로그램의 크기가 커지면 이러한 내용을 적어주는 것이 중요하다.



  • if not 변수:
)
while True:
  a=input("값을 입력")
  if not a:  
     break 
  for i in a:
      print(a)

if문은 참이어야 실행한다.
if not a:에서 'a가 not이어야'(=a값이 없어야) 참이된다.
a는 input을 통해 값을 전달받는 변수다.
즉 'a가 not'이라는 뜻은 입력받는 값이 없는 경우다.
따라서 입력을 받지 못했을 때 if문이 실행되고 break로 나오게된다.
만약 입력받는 값이 있는 경우에는 for문에 따라 print를 실행한다.


  • rjust() ljust() center()
)
rjust(전체 자리숫자, 공백이 있을 때 공백을 채울 텍스트) # 오른쪽 정렬
ljust(전체 자리숫자, 공백이 있을 때 공백을 채울 텍스트) # 왼쪽 정렬
center(전체 자리숫자, 공백이 있을 때 공백을 채울 텍스트) # 가운데 정렬


  • 파일 open시 encoding 에러가 나오는 경우

UnicodeDecodeError: 'cp949' codec can't decode byte 0xed in position 6: illegal multibyte sequence 은 encoding='cp949' 대신 encoding='utf-8' 하니까 해결됨
'cp949'으로 인코딩된 파일을 못 읽어와서 생기는 문제기 때문이다.
따라서 encoding='utf-8'으로 인코딩 방식을 바꿔주면 해결된다.
'cp949' 대신 'utf-8' 오류가 나온 경우 반대로 encoding='cp949'를 넣어줘야 한다.


  • 주소록 만들기 헷갈렸던 부분들
1)
class Person:
     def __init__(self,name,phone,addr):
          self.name=name
          self.phone=phone
          self.addr=addr

          while True:
               buffer=file.readline()
               name=buffer.split(',')[0]
               phone=buffer.split(',')[1]
               addr=buffer.split(',')[2].rstrip('\n')
               #읽어온 정보를 어딘가에 저장 각 사람의 정보를 세트로 저장해주려면 class를 사용해야함
               address_List.append(Person(name,phone,addr))2)
    for person in address_List:
          file.write('{},{},{}'.format(person.name,person.phone,person.addr)) 
          #파일에 다시써주는데 바로 file.write(person)으로 쓰면 안된다. 
          #왜냐면 csv파일은 ','로 구분되기 때문이다. 

profile
서버개발 공부중

0개의 댓글