<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    海上月明

    editer by sun
    posts - 162, comments - 51, trackbacks - 0, articles - 8
       :: 首頁 :: 新隨筆 ::  :: 聚合  :: 管理

    [轉]Gems of Python

    Posted on 2008-11-11 09:41 pts 閱讀(433) 評論(0)  編輯  收藏 所屬分類: Python
    Gems of Python - Eric Florenzano's Website
    Gems of Python

    * Tags:
    * programming,
    * python

    Posted on Nov. 2, 2008 at 4:04 P.M.

    I've been using Python for a few years now, and continue to love it. But the language is large enough that it seems every project that I look at uses a different subset of the language's features. The nice thing is that by reading different people's code, you can find out about some real gems in the Python programming language. Some of these tips are extremely obvious, and some are more obscure. In any case, here are what I consider to be some real gems:

    1.

    filter This is one of Python's built-in functions, which allows you to remove unwanted items from a list. It's very useful and highly overlooked. Here's an example of how to use it:

    >>> lst = ['1', '2', '3', '4', 'asdf', '5']
    >>> def is_int_string(i):
    ... try:
    ... int(i)
    ... return True
    ... except ValueError:
    ... return False
    ...
    >>> int_string_list = filter(is_int_string, lst)
    >>> int_string_list
    ['1', '2', '3', '4', '5']

    But there is a really neat filter shortcut, too. You can have it filter out any values which evaluate to False.

    >>> lst = [0, 2, '', 'asdf', None, [], (), 'fdsa']
    >>> filter(None, lst)
    [2, 'asdf', 'fdsa']

    This is really great for filtering out unwanted values in a list. I use it actually quite frequently and hope to see it in more python projects.
    2.

    itertools.chain I often have a list of lists, and want to run some operation on each item in that list of lists. itertools.chain allows that to happen. Let me demonstrate with an example:

    >>> import itertools
    >>> lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> list(itertools.chain(*lst))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> sum(itertools.chain(*lst))
    45

    itertools.chain has become a major part of my day-to-day coding toolbox, and it's a real python gem.
    3.

    setdefault Do you find yourself writing this type of try..except KeyError pattern often?

    >>> dct = {}
    >>> items = ['anne', 'david', 'kevin', 'eric', 'anthony', 'andrew']
    ... for name in items:
    ... try:
    ... dct[name[0]].append(name)
    ... except KeyError:
    ... dct[name[0]] = [name]
    >>> dct
    {'a': ['anne', 'anthony', 'andrew'], 'k': ['kevin'], 'e': ['eric'], 'd': ['david']}

    That's a lot of boilerplate code for something that seems like it should be much easier. Thankfully, this can be solved much more easily by using setdefault, like so:

    >>> dct = {}
    >>> items = ['anne', 'david', 'kevin', 'eric', 'anthony', 'andrew']
    >>> for name in items:
    ... dct.setdefault(name[0], []).append(name)
    ...
    >>> dct
    {'a': ['anne', 'anthony', 'andrew'], 'k': ['kevin'], 'e': ['eric'], 'd': ['david']}

    Much better, isn't it?
    4.

    defaultdict Given setdefault, it still seems like there should be a better way. If you know upfront that you will be setting everything to an empty list if it isn't found, you should be able to specify that and have it just Do The Right Thing. Thankfully, defaultdict does just that:

    >>> from collections import defaultdict
    >>> dct = defaultdict(list)
    >>> items = ['anne', 'david', 'kevin', 'eric', 'anthony', 'andrew']
    >>> for name in items:
    ... dct[name[0]].append(name)
    ...
    >>> dct
    defaultdict(, {'a': ['anne', 'anthony', 'andrew'], 'k': ['kevin'], 'e': ['eric'], 'd': ['david']})
    >>> dict(dct)
    {'a': ['anne', 'anthony', 'andrew'], 'k': ['kevin'], 'e': ['eric'], 'd': ['david']}

    I usually end up converting the defaultdict back to a regular dict before passing it around, but other than that, it's quite a useful tool to use.
    5.

    zip This is one that most people usually know, but still I find that sometimes people do strange things where a zip would be much easier.

    >>> numbers = [1, 2, 3, 4, 5]
    >>> letters = ['a', 'b', 'c', 'd', 'e']
    >>> for num, let in zip(numbers, letters):
    ... print "Letter %d is '%s'" % (num, let)
    ...
    Letter 1 is 'a'
    Letter 2 is 'b'
    Letter 3 is 'c'
    Letter 4 is 'd'
    Letter 5 is 'e'

    Pretty simple, very common, and yet sometimes coders seem to work around it. Also worth mentioning is that there's an iterable version of this, izip, which is located in itertools.
    6.

    title I wrote some little function to turn a string of lower case text into a 'titleized' string at work, and a few coworkers laughed and said, "why didn't you just use title"? The answer: I didn't know about it. It's not something you run into every day, but when you need it, it's super useful. Here's an example:

    >>> s = 'the little green men'
    >>> s.title()
    'The Little Green Men'

    It's that easy! Next time you need to turn something into a title, look for this method on strings first.

    That's all I've got for now. There are many more gems in the Python programming language, but these are some that I think are especially useful. Please share in the comments if you have any other gems that you have found in your uses of Python.

    UPDATE: Eric Holscher has posted a list of his Python gems as well, and it's got some great stuff on it. Check it out!
    主站蜘蛛池模板: 亚洲欧洲日产国码二区首页| 久久亚洲高清综合| 亚洲精品国产成人| 国产在线精品免费aaa片| 亚洲真人无码永久在线| 2022国内精品免费福利视频| 免费在线观看你懂的| 老司机亚洲精品影院在线观看| 成年女人喷潮毛片免费播放| 亚洲国产成人精品激情| 欧美三级在线电影免费| 久久久久亚洲国产| 在线观看免费亚洲| 最新亚洲人成无码网www电影| 四虎AV永久在线精品免费观看| 特级毛片免费观看视频| 久久久久久久亚洲精品| 成人免费一区二区三区| 亚洲欧洲第一a在线观看| 67194成手机免费观看| 亚洲成无码人在线观看| 成人免费视频一区| 国产精品亚洲一区二区三区在线观看| 亚洲第一页日韩专区| 三上悠亚在线观看免费| 99人中文字幕亚洲区| 成年在线网站免费观看无广告| 亚洲国产精品日韩av不卡在线| 亚洲成av人片天堂网老年人| 免费日本一区二区| 亚洲AV无码久久久久网站蜜桃 | 国产精品综合专区中文字幕免费播放| 亚洲另类少妇17p| 免费日本一区二区| 在线观看亚洲AV日韩AV| JLZZJLZZ亚洲乱熟无码| 91精品国产免费网站| 朝桐光亚洲专区在线中文字幕| 久久亚洲精品国产精品黑人| 免费无码又黄又爽又刺激| 亚洲免费无码在线|