[Dynamic Language] Python Tips

Python Tips, 持续更新中...
          
Python Slicing 序列切片

代码
In [1]: l = [1,2,3,4]
In [
2]: l[1:3]
Out[
2]: [2, 3]

In [
4]: l[1:] //省略结束
Out[
4]: [2, 3, 4]

In [
5]: l[:2] //省略开始
Out[
5]: [1, 2]

In [
8]: l[::-1] //基数倒排序
Out[
8]: [4, 3, 2, 1]

In [
9]: l[::2] //基数取索引为偶数项
Out[
9]: [1, 3]

In [9]: l[-2:] //取后两项
Out[
9]: [ 3, ]

Python 列表推导

l = [1,2,3,4,5,6]
result1
= [x+1 for x in l]
相当于以下代码:
result2
= []
for x in l :
result2.append(x
+1)


result3
= [x+1 for x in l if x > 3]
相当于以下代码:
result4
= []
for x in l:
if x > 3:
result4.append(x
+1)


l2
= [4,5,6]
result5
= [x+y for x in l if x>4 for y in l2 if y>5]
相当于以下代码:
result6
= []
for x in l:
if x > 4:
for y in l2:
if y > 5:
result6.append(x
+y)

字典转化

In [11]: l = [(1,2), (3,4),(5,6)]

In [
12]: d = dict(l)

In [
13]: d
Out[
13]: {1: 2, 3: 4, 5: 6}

转化为10进制数

In [45]: int("101", 2)
Out[
45]: 5

In [
46]: int("10", 8)
Out[
46]: 8

In [
47]: int("0xa", 16)
Out[
47]: 10

all 、any

In [6]: print all( x > -1 for x in range(10))
True

In [
7]: print all( x > 1 for x in range(10))
False

In [9]: print any( x > 1 for x in range(10))
True

In [
10]: print any( x > 11 for x in range(10))
False

一行代码求字符串中字串的个数

In [14]: "abcaba".count('a')
Out[
14]: 3

一行代码求列表的乘积

In [16]: reduce(lambda x,y: x*y, [1,2,3])
Out[
16]: 6

posted @ 2010-12-04 20:13  ABeen  阅读(269)  评论(0编辑  收藏  举报