Differences between revisions 3 and 4
Revision 3 as of 2006-04-22 16:13:21
Size: 2119
Editor: HuangYi
Comment:
Revision 4 as of 2006-04-22 16:29:45
Size: 1964
Editor: HuangYi
Comment:
Deletions are marked like this. Additions are marked like this.
Line 13: Line 13:
我以为你永远也不会问这种问题。如果你把矩阵当做序列的序列的话,只要用zip就可以搞定:
Line 21: Line 23:

要理解这个, 你要先搞清楚 f(*m) 和 apply(f, m) 是一样的。这是基于一个古老的 Lisp 的问题, 答案就是这个和 map(None,*m) 等价的东西, 不过用 zip 的这段程序甚至更短一点。 你可能会想这个只不过对 Letterman's Stupid Programmer's Tricks 的出现有点用而已, 但是有一天, 我遇到了这个问题: 提供一个数据库行的列表, 每一行都是一个排好序了的值的列表, 要你找出这么一个列表, 他里面的值在每 ( '''这一句翻不出来了啊, 哪位兄弟来帮一把啊'''), 于是我这么写下:
Line 27: Line 32:
我以为你永远也不会问这种问题。如果你把矩阵当做序列的序列的话,那么zip就可以完成这个任务:

{{{
#!python
>>> m = [(1,2,3), (4,5,6)]
>>> zip(*m)
[(1, 4), (2, 5), (3, 6)]
}}}
要理解这个, 你要先搞清楚 f(*m) 和 apply(f, m) 是一样的。这是基于一个古老的 Lisp 的问题, 答案就是这个和 map(None,*m) 等价的东西, 不过用 zip 的这段程序甚至更短一点。 你可能会想这个只不过对 Letterman's Stupid Programmer's Tricks 的出现有点用而已, 但是有一天, 我遇到了这个问题: 提供一个数据库行的列表, 每一行都是一个排好序了的值的列表, 要你找出这么一个列表, 他里面的值在每 ( '''这一句翻不出来了啊, 哪位兄弟来帮一把啊'''), 于是我这么写下:

{{{
#!python
possible_values = map(unique, zip(*db))
}}}

返回::[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:

   1 >>> m = [(1,2,3), (4,5,6)]
   2 >>> zip(*m)
   3 [(1, 4), (2, 5), (3, 6)]

要理解这个, 你要先搞清楚 f(*m) 和 apply(f, m) 是一样的。这是基于一个古老的 Lisp 的问题, 答案就是这个和 map(None,*m) 等价的东西, 不过用 zip 的这段程序甚至更短一点。 你可能会想这个只不过对 Letterman's Stupid Programmer's Tricks 的出现有点用而已, 但是有一天, 我遇到了这个问题: 提供一个数据库行的列表, 每一行都是一个排好序了的值的列表, 要你找出这么一个列表, 他里面的值在每 ( 这一句翻不出来了啊, 哪位兄弟来帮一把啊), 于是我这么写下:

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))

PyIAQ/Q11 (last edited 2009-12-25 07:14:04 by localhost)