今天在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:
4. iter()能使用callable的参数>>> 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)
For instance:
def seek_next_line(f): for c in iter(lambda: f.read(1),'\n'): pass
The
iter(callable, until_value)
function repeatedly callscallable
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:
6. 列表的一些切片的trick>>> def foo(x=None): ... if x is None: ... x = [] ... x.append(1) ... print x >>> foo() [1] >>> foo() [1]
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
andb
.After the assignment, the new tuple is unreferenced and marked for garbage collection, and the values bound to
a
andb
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.