Snowwwolf's Blog

My Blog, My Work, My Life.

Python Tips

enumerate

enumerate 用于遍历, 与for in相比, 可同时返回index和element

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> for i, elem in enumerate(seasons):
...   print i, elem
... 
0 Spring
1 Summer
2 Fall
3 Winter
>>> 

Counter

collection.Counter 专用于计数

>>> from collections import Counter
>>> c = Counter('ABBEDDAD')
>>> c.keys()
['A', 'B', 'E', 'D']
>>> c.values()
[2, 2, 1, 3]
>>> c.items()
[('A', 2), ('B', 2), ('E', 1), ('D', 3)]

map & reduce

map & reduce 是Map-Reduce中的map(注意不是C++ STL中的树容器map)和reduce

map用于对每一个元素执行一个一元函数/lambda

reduce用于对初值或当前结果与每一个元素执行一个二元函数/lambda, 得到下一个结果, 再与下一个元素执行这个二元函数/lambda

参考:

>>> map(lambda x:x+x,range(5))   #lambda 函数,各项+本身
[0, 2, 4, 6, 8]
>>> reduce(add,range(11))        #1+2+3+...+10
55

Conditional Expression

Conditional Expression:

x = true_value if condition else false_value

Python缺少三元 condition ? true_value : false_value 运算符, 所以当需要实现这种逻辑的时候, 之前喜欢用 condition and true_value or false_value 的方式. 但是这种方式很容易出bug, 比如 condition ? 0 : 1, 就会发现无论condition, 总是返回1. (虽然可以用 condition ? [0]: [1])[0] 解决, 但是太丑了)

PEP308 建议通过这种Conditional Expression的方式实现

Setup Octopress on My MacOS

To describe the setup process on my Mac OS 10.8.

Referenced from http://octopress.org/docs/setup/

  1. Download Octopress

    git clone git://github.com/imathis/octopress.git octopress

  2. Install ruby 1.9.3. (Note that only ruby 1.9.3, NOT 1.9.3 or above)

    brew install rbenv

    brew install ruby-build

    rbenv install 1.9.3-p0

    rbenv rehash

  3. Modify content of .ruby-version file in octopress to “1.9.3-p0”. Run “ruby —version” should report “Ruby 1.9.3-p0”

  4. Final setup commands

    gem install bundler

    rbenv rehash

    bundle install

    rake install

Simple Instruction for Octopress

referenced from official docs of octopress http://octopress.org/docs/blogging/

New Post

cd /path/to/octopress
rake new_post['title']
<edit /path/to/octopress/source/_post/YYYY-mm-dd-title.markdown>
rake generate
(if want to preview:
    rake watch
    rake preview (or use [pow](http://pow.cx/))
)
rake deploy

ps. Recommend Mou as markdown editor for OSX

Modify Anything Else

e.g. _config.yaml modified

rake generate
rake deploy

Git Push

git commit add …

git commit -m’…’

git push origin source

First Post

这是部署Octopress后的first post

用Octopress纯粹为了好玩,也因为Octopress号称是”A blogging framework for hackers”

说不定能激发继续写blog的热情

过去写的blog,请移步http://blog.csdn.net/shuiyu