Size: 1963
Comment:
|
Size: 2026
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 24: | Line 24: |
要理解这个, 你要先搞清楚 f(*m) 和 apply(f, m) 是一样的。这是基于一个古老的 Lisp 的问题, 答案就是这个和 map(None,*m) 等价的东西, 不过用 zip 的这段程序甚至更短一点。 你可能会想这个只不过对 Letterman's Stupid Programmer's Tricks 的出现有点用而已, 但是有一天, 我遇到了这个问题: 提供一个数据库行的列表, 每一行都是一个排好序了的值的列表, 要你找出这么一个列表, 他里面的值在每 ( '''这一句翻不出来了啊, 哪位兄弟来帮一把啊'''), 于是我这么写下: | 如果你知道 f(*m) 和 apply(f, m) 是等价的,你就可以理解上面的代码。这个提问源于一个古老的 Lisp 的问题, 答案等价于 Python 的 map(None,*m) 函数, 不过 Chih-Chung 建议的 zip 版本甚至可以做到更短。 你可能会想这只不过是一个无聊的最短程序把戏. 可是有一天我遇到了类似的问题: 提供一个数据库记录列表, 每一条记录都是一个有序的值列表, 要你找出每一列出现的唯一值(无重复值)的列表, 于是我写下这行代码: {{{ #!python possible_values = map(unique, zip(*db)) }}} |
Line 32: | Line 36: |
... WeiZhong 擅自修改了你的译文,请见谅. |
返回::[wiki:self:PyIAQ Python 罕见问题集]
::-- ["huangyi"] [DateTime(2006-04-22T16:08:15Z)] TableOfContents
::-- ZoomQuiet [DateTime(2005-09-06T04:10:30Z)] TableOfContents
1. 问:嘿, 你可以在0.007kb以内的代码里转置一个矩阵吗?
Q: Hey, can you write code to transpose a matrix in 0.007KB or less?
我以为你永远也不会问这种问题。如果你把矩阵当做序列的序列的话,只要用zip就可以搞定:
I thought you'd never ask. If you represent a matrix as a sequence of sequences, then zip can do the job:
如果你知道 f(*m) 和 apply(f, m) 是等价的,你就可以理解上面的代码。这个提问源于一个古老的 Lisp 的问题, 答案等价于 Python 的 map(None,*m) 函数, 不过 Chih-Chung 建议的 zip 版本甚至可以做到更短。 你可能会想这只不过是一个无聊的最短程序把戏. 可是有一天我遇到了类似的问题: 提供一个数据库记录列表, 每一条记录都是一个有序的值列表, 要你找出每一列出现的唯一值(无重复值)的列表, 于是我写下这行代码:
1 possible_values = map(unique, zip(*db))
To understand this, you need to know that f(*m) is like apply(f, m). This is based on an old Lisp question, the answer to which is Python's equivalent of map(None,*m), but the zip version, suggested by Chih-Chung Chang, is even shorter. You might think this is only useful for an appearance on Letterman's Stupid Programmer's Tricks, but just the other day I was faced with this problem: given a list of database rows, where each row is a list of ordered values, find the list of unique values that appear in each column. So I wrote:
1 possible_values = map(unique, zip(*db))
... WeiZhong 擅自修改了你的译文,请见谅.