python一些有用但是很少人知道的技巧

今天在stack overflow上看到了一个帖子,上面汇集了一些python的隐藏属性,感觉有一些还是挺不错,记录了一些下来:

1. 比较符号链接

>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20 
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True

In case you're thinking it's doing 1 < x, which comes out as True, and then comparing True < 10, which is also True, then no, that's really not what happens (see the last example.) It's really translating into 1 < x and x < 10, and x < 10 and 10 < x * 10 and x*10 < 100, but with less typing and each term is only evaluated once.

2. 列举(enumerate)

Wrap an iterable with enumerate and it will yield the item along with its index.

For example:


>>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a): print index, item
...
0 a
1 b
2 c
3 d
4 e
>>>

References:

  • Python tutorial—looping techniques
  • Python docs—built-in functions—enumerate
  • PEP 279
    这个方法对我们习惯在c/java中写i的同学很实用。

    3. 生成器(Creating generators objects)

    If you write

    x=(n for n in foo if bar(n))

    you can get out the generator and assign it to x. Now it means you can do

    for n in x:

    The advantage of this is that you don't need intermediate storage, which you would need if you did

    x = [n for n in foo if bar(n)]

    In some cases this can lead to significant speed up.

    You can append many if statements to the end of the generator, basically replicating nested for loops:

    >>> n = ((a,b) for a in range(0,2) for b in range(4,6))
    >>> for i in n:
    ...   print i 
    
    (0, 4)
    (0, 5)
    (1, 4)
    (1, 5)
    4. iter()能使用callable的参数

    For instance:

    def seek_next_line(f):
        for c in iter(lambda: f.read(1),'\n'):
            pass

    The iter(callable, until_value) function repeatedly calls callable and yields its result untiluntil_value is returned.

    5.注意那些不可变的缺省参数

    Be careful with mutable default arguments

    >>> def foo(x=[]):
    ...     x.append(1)
    ...     print x
    ... 
    >>> foo()
    [1]
    >>> foo()
    [1, 1]
    >>> foo()
    [1, 1, 1]

    Instead, you should use a sentinel value denoting "not given" and replace with the mutable you'd like as default:

    >>> def foo(x=None):
    ...     if x is None:
    ...         x = []
    ...     x.append(1)
    ...     print x
    >>> foo()
    [1]
    >>> foo()
    [1]
    6. 列表的一些切片的trick

    The step argument in slice operators. For example:

    a = [1,2,3,4,5]
    >>> a[::2]  # iterate over the whole list in 2-increments
    [1,3,5]

    The special case x[::-1] is a useful idiom for 'x reversed'.

    >>> a[::-1]
    [5,4,3,2,1]
    

    6. 原地交换两个变量的值:In-place value swapping

    >>> a = 10
    >>> b = 5
    >>> a, b
    (10, 5)
    
    >>> a, b = b, a
    >>> a, b
    (5, 10)

    The right-hand side of the assignment is an expression that creates a new tuple. The left-hand side of the assignment immediately unpacks that (unreferenced) tuple to the names a and b.

    After the assignment, the new tuple is unreferenced and marked for garbage collection, and the values bound to a and b have been swapped.

    As noted in the Python tutorial section on data structures,

    Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

    http://stackoverflow.com/questions/101268/hidden-features-of-python#101447
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值