Skip to content
daclouds edited this page Jul 7, 2013 · 7 revisions

if

if suffix == ".htm":
  content = "text/html"
elif suffix == ".jpg":
  content = "image/jpeg"
else:
  raise RuntimeError("Unknown content type")

while

f = open("foo.txt")
line = f.readline()
while line:
  print line,
  line = f.readline()
...
f.close

for

for line in open("foo.txt")
  print line,

itertools

python docs

Quiz

1. comma 추가하기

예)  
     입력 1000000
     출력 1,000,000
>>> a = "1000000"
>>> b = a[::-1]
>>>
>>> for i in range(len(b)):
...   if (i % 3 == 0 and i != 0): result += "," + b[i]
...   else: result += b[i]
...
>>> result
'000,000,1'
>>> result[::-1]
'1,000,000'

2. read and say

1
1 1
1 2
1 1 2 1
1 2 2 1 1 1
1 1 2 2 1 3
1 2 2 2 1 1 3 1
1 1 2 3 1 2 3 1 1 1
1 2 2 1 3 1 1 1 2 1 3 1 1 3
1 1 2 2 1 1 3 1 1 3 2 1 1 1 3 1 1 2 3 1
>>> import itertools
>>> seq = [1]
>>> for i in range(10):
...     print ' '.join(map(str, seq))
...     seq2 = []
...     for key, subgroup in itertools.groupby(seq):
...         seq2 += [key, len(list(subgroup))]
...     seq = seq2
...

ask.python.kr ( falsetru )

Clone this wiki locally