[Python] 생성기
def gene(n): print “Generator start” while n < 10: yield n #현재 n 값을 반환, 생성기 자체는 종료되지 않고 멈춰있음 n += 1 print “Generator end” for i in gene(1): #순차적으로 생성기 호출 (next) print i ... Read more
def gene(n): print “Generator start” while n < 10: yield n #현재 n 값을 반환, 생성기 자체는 종료되지 않고 멈춰있음 n += 1 print “Generator end” for i in gene(1): #순차적으로 생성기 호출 (next) print i ... Read more
f=open(“C:\Windows\System32\drivers\etc\hosts”) #파일 객체 생성 f2=open(“out.log”,”w”) line=f.readline() #파일 read while line: print line, # ,는 줄바꿈 생략 #print(line,end=”) #파이썬3 print >>f2,line # f2에 line 내용 출력 #print(line,file=f2) #파이썬3 line=f.readline() f.close() for line2 in open(“C:\Windows\System32\drivers\etc\hosts_tmp”): print line2,
count=0 def func(a,b=1): #두번째 인수에 기본값 설정 “func() is tutorial function” #함수 문서화 문자열 global count #전역 변수를 함수 내에서 사용 count += 1 print “call count : %d” % count print a,”+”,b return a+b print func(4,5) print func(9) print func.__doc__
tuple1 = (“123″,”456″,789,”data”) item1,item2,item3,item4 = tuple1 #차례대로 데이터 대입 tuple2 = ( ) #빈 튜플 생성 tuple3 = (“123”,) #1개 요소 튜플 생성 tuple4 = “123”, #1개 요소 튜플 생성
set1 = set([1,2,3,4]) set2 = set(“hello”) #중복값은 제거됨 (helo) set1.add(5) #값 1개 추가 set1.update([6,7,8]) #값 여러개 추가 set2.remove(‘e’) #값 제거 set1 | set2 #합집합 set1 & set2 #교집합 set1 – set2 #차집합 set1 ^ set2 #대칭차집합 (교집합 반대)
dic1 = {“item1” : “123”, “item2” : 456, “item3” : “data”} dic2 = {} #빈 사전 생성 dic3 = dict() #빈 사전 생성 dic1[“item4”] = “data2” #키 추가 del dic1[“item3”] #키 삭제 if “item2” in dic1: #사전에 해당 키가 있는지 확인 i=dic1[“item2”] else: i=0 j=dic1.get(“item2”,0) … Read more
list1 = [“123″,”456″,”abc”] list1[0] #색인은 0부터 (0~2) list1.append(“new data”) #새 항목 추가 list1.insert(1,”ins”) #idx 1위치에 항목 추가 list1[1:2] #idx 1부터 idx 2 이전까지 (idx 1만 출력) list1[1:] #idx 1부터 끝까지 list2=[] #빈 리스트 생성 list3=list() #빈 리스트 생성
data1 = range(1,10) #1~9의 값을 가지는 리스트 생성 data2 = 0 for i in data1: print i while data2 < 10: data2+=1 if data2 % 2: print data2, #홀수면 출력 else: continue #짝수면 아래 구문 무시하고 반복문 ... Read more
#조건문 a=1 b=2 c=3 d=4 s=”show me the money” x=[1,2] y=[1,2] if a < b: print “bbbb” elif b < a: print “aaaa” else: print “aabb” if a < b and b < c and not (d < c): print “dddd” if “money” in s: # 좌측 ... Read more
import sys i=0.5353 s=”text” t=sys.argv[0] #명령줄 인수를 읽어옴 print “Hello World %.2f %d” % (i,2016) # 파이썬 3에서는 print 다음에 ()가 들어감 ex: print(“Hello World %.2f %d” % (i,2016)) print “file name is %s” % (t) print format(i,”10.2f”),format(s,”20s”),”123″ #format 함수의 2번째 인자는 포맷지정자 sys.stdout.write(“input : “) t=sys.stdin.readline() print t t= raw_input(“input : “) … Read more