« 脱ひきこもり野菜日記 |Main| 起きられなかった日記 »

« Pythonにおけるタプルの存在意義 リターンズ | Python | Jythonでハノイの塔の可聴化 »

PythonでRubyっぽいmap

思いつきでやった。
>>> Array([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> _.map("""|x|
	if x % 2 == 0:
		return x / 2
	else:
		return x * 3 + 1""")
[4, 1, 10, 2, 16]

種明かしは下記

>>> class Array(list):
	def map(self, code):
		import re
		m = re.match("\|(.*?)\|(.*)", code, re.DOTALL)
		d = {}
		exec("def foo(%s):\n%s" % m.groups(), d)
		return map(d["foo"], self)

トラックバック(Trackback)

Trackback URL: http://www.nishiohirokazu.org/mt/mt-tb.cgi/516

ご意見・ご感想をお送りください(フィードバック)

(フィードバックはメールで送信され、基本的に表示されませんが、内容によっては公開させていただくこともございます。ご了承ください。Your comment doesn't appear the page immediately. If the comment has value to other people, it will be put on the page or subsequent entries. Thank you.)

上の情報は、いずれも未記入でかまいません。 All of above questions are optional.