Differences between revisions 4 and 5
Revision 4 as of 2008-01-28 20:04:52
Size: 3698
Editor: 203
Comment:
Revision 5 as of 2008-01-28 20:05:17
Size: 3700
Editor: 203
Comment:
Deletions are marked like this. Additions are marked like this.
Line 110: Line 110:
== 파일생성일 == === 파일생성일 ===

[Python]쓰면서 각종 팁 정리. SeeAlso BioPythonTip, PythonNewFunction

TableOfContents

string formatting

   1 >>> template = "My name is %s and I have %i won" 
   2 >>> print template 
   3 My name is %s and I have %i won 
   4 >>> template % ("yong", 1000) 
   5 'My name is yong and I have 1000 won' 
   6 >>> 
   7 >>> template = "My name is %(name)s and I have %(money)i won"  
   8 >>> print template                                                                          
   9 My name is %(name)s and I have %(money)i won 
  10 >>> template % {'name':'yong','money':1000} 
  11 'My name is yong and I have 1000 won' 
  12 >>> 
  13 >>> name = 'yong' 
  14 >>> money = 1000 
  15 >>> template % vars() 
  16 'My name is yong and I have 1000 won' 
  17 >>> 

항목갯수에 따라 달라지는 string formatting

   1 >>> template = "There are %i event%s"                                                        
   2 >>> 
   3 >>> events = ['a'] 
   4 >>> template%(len(events), len(events)>1 and 's' or '') 
   5 'There are 1 event' 
   6 >>> 
   7 >>> events = ['a','b']                                                                        
   8 >>> template%(len(events), len(events)>1 and 's' or '') 
   9 'There are 2 events' 
  10 >>> 

HTML따위 생성시 list comprehension 이용

   1 >>> events = ['a','b','c']                                                            
   2 >>> ''.join(['<li>%s</li>'%x for x in events]) 
   3 '<li>a</li><li>b</li><li>c</li>' 
   4 >>> 

IF문대용으로 쓰는 논리연산

   1 >>> checkSign = lambda aInt: aInt>0 and 'positive' or aInt==0 and 'zero' or 'negative'                      
   2 >>> 
   3 >>> checkSign(1)
   4 'positive'
   5 >>> checkSign(0)
   6 'zero'
   7 >>> checkSign(-1)
   8 'negative'
   9 >>> 

설마 그런 코드를 진짜로 사용하시려는 것은 아니시죠? 가능하다는 것과 실제로 사용하는 것에는 큰 차이가 있다고 생각하는데, 위의 코드가 바로 그런 경우가 아닐까 합니다. 저라면 위와 같이 코드 작성하는 사람은 절대 고용하지 않을 듯 하군요. 한가지 더 보태자면, 위와 같은 함수보다는 True, False 만을 리턴하는 isPositive나 isNegative가 (경험상) 더 유용하리라고 생각합니다. checkSign(1)이 'positive'를 리턴한다면 positive인지 알려면 또한번 비교해야 하니까요. 짧은 코드지만 작성한 사람에 대해 여러가지 알아낼 수 있다는 것을 보여주는 코드네요. --Anonymous

  • 논리연산을 if문 처럼 쓸수있다는 것을 보인 예일 뿐입니다. ; --[yong27], 2004-11-17 (->) [Factorial.py] 짧은 코멘트지만 작성한 사람에 대해 여러가지 알아낼 수 있다는 것을 보여주는 코멘트네요. --[windist]

Multidimensional list

   1 w,h = 2,3
   2 A = [ [None]*w for i in range(h) ]
   3 # don't use [[None]*w]*h

SeeAlso [http://bbs.python.or.kr/viewtopic.php?t=21226 리스트 2차원배열]

사전의 setdefault

   1 >>> d = {}
   2 >>> if 'a' not in d:
   3 ...     d['a'] = []
   4 ... 
   5 >>> d['a'].append(1)
   6 >>> d
   7 {'a': [1]}
   8 >>> d.setdefault('b',[]).append(2)
   9 >>> d
  10 {'a': [1], 'b': [2]}
  11 >>> 

shelve 쓸때 주의

   1 >>> d=shelve.open('test.db')
   2 >>> d['a']=[]
   3 >>> d['a'].append(1)
   4 >>> d['a']  # 1 is not appended
   5 []
   6 >>> d['b'] = []
   7 >>> temp = d['b']
   8 >>> temp.append(1)
   9 >>> d['b'] = temp
  10 >>> d['b'] # you have to use temp variable
  11 [1]
  12 >>> d2=shelve.open('test.db',writeback=True)  # It will work as you expected, but it use a lot of memories

파일생성일

get_file_mtime = lambda f: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.stat(f)[8]))

PythonTip (last edited 2012-07-06 09:02:36 by 61)

web biohackers.net