Differences between revisions 5 and 6
 ⇤ ← Revision 5 as of 2004-10-05 01:04:51 → Size: 6172 Editor: 221 Comment: ← Revision 6 as of 2004-10-06 00:12:55 → ⇥ Size: 6310 Editor: hoxide Comment: Deletions are marked like this. Additions are marked like this. Line 201: Line 201: 数组排序中讲的方法真的会快点吗? 真的快到我们值得放弃直接用sort得到得可读性吗?值得怀疑 -- hoxide

Python编程速度技巧 -- Zoom.Quiet [DateTime(2004-08-09T23:59:25Z)]

TableOfContents [转载自oso，其上有“python编程简介”系列，这是第九篇，是篇译文] 有了前面的描述, 大家差不多知道什么是Python了. 最近因为在网 上看一两篇关于Python的运行速度问题, 不给大家介绍一下心里不 踏实,

# Python编程速度技巧

## 最常见

• 一个最常见的速度陷坑(至少是俺在没看到网上这篇介绍时陷进去

```   1 shortStrs = [ str0, str1, ..., strN]
2 #N+1个字串所组成的数列
3 longStr = ''
4 for s in shortStrs: longStr += s
```

### 找出速度瓶颈

• 1)首先在大家应先学会怎么去找出速度瓶颈: Python自带有profile

```   1 import profile
2 profile.run ('想要检查的函数名()')
```

### 字串相并

• 就头上的例子而言, 用 :

```   1 longStr =''.join(shortStrs)
```

```   1 shortStrs = [str(s) for s in shortStrs[i]]
2 longStr = ''.join(shortStrs)
```

• list.sort ()

### 循环

```   1 import string
2 newL = []
3 for s in l: newL.append( string.upper(s) )
```

```   1 import string
2 newL = map (string.upper, l)
```

Guido的文章讲得很详细.

### 局域变量 及 '.'

```   1 import string
2 append = newL.append
3 for s in l: append (string.upper(s))
```

```基本循环: 3.47秒

### try的使用

```   1 count = {}
2 for s in l:
3     if not count.has_key(s): count[s] = 0
4     else: count[s] += 1
```

```   1 count ={}
2 for s in l:
3     try: count[s] += 1
4     except KeyError: count[s] = 0
```

### 大量数据处理

```   1 def f():
2 for d in hugeData: ...
3 f()
```

```   1 def f(d): ...
2 for d in hugeData: f(d)
```

### 减少周期性检查

`---编/译完毕. 看来Python是易学难精了, 象围棋? `