Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created July 21, 2012 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwatch/3154975 to your computer and use it in GitHub Desktop.
Save kwatch/3154975 to your computer and use it in GitHub Desktop.
もしPythonの内包表記に終了条件が指定できたら
##
## フィボナッチ数列のうち100以下のものを求める
##
def fibgen():
x, y = 0, 1
while True:
yield x
x, y = y, x+y
## 現在のやり方
answer = []
for n in fibgen():
if n > 100:
break
answer.append(n)
## or
answer = []
g = fibgen()
n = next(g)
while n <= 100:
answer.append(n)
n = next(g)
## もし内包表記に終了条件を指定できたら
answer = [ n for n in fibgen() while n <= 100 ]
##
## HTTPレスポンスを記録したファイルのうちヘッダだけを取り出す
## (=最初の空行の直前までを取り出す)
##
## 現在のやり方
lines = []
with open('http.data') as f:
for line in f:
if line == "\n":
break
lines.append(line)
## 内包表記に終了条件をつけることができたら
with open('http.data') as f:
lines = [ line for line in f while line != "\n" ]
##
## 上と似ているけど行の配列ではなく辞書として取り出す
##
## 現在のやり方
headers = {}
with open('http.data') as f:
for line in f:
if line == "\n":
break
name, value = line.split(':', 1)
headers[name] = value.strip()
## もし内包表記に終了条件を指定できたら
with open('http.data') as f:
g = ( line.split(': ', 1) for line in f whie line != "\n")
headers = { name:value.strip() for name, value in g }
##
## 1行ごとに日付と値が書かれたデータを標準入力から読み込み、
## 今日のぶんだけを取り出す
## (たとえば 'git log --date=short --pretty=format:"%ad: %s"' のように
## 最新のデータほど前にあることを仮定している)
##
import re, datetime
rexp = re.compile(r'^(\d\d\d\d-\d\d-\d\d) (.*)', re.M)
today = str(datetime.date.today())
with open('hoge.data') as f:
content = f.read()
## 現在のやり方
values = []
for m in rexp.finditer(content):
date, value = m.groups()
if date != today:
break
values.append(value)
## もし内包表記に終了条件を指定できたら
values = [ m.group(2) for m in rexp.finditer(content) while m.group(1) == today ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment