返回::[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??
I thought you'd never ask. If you represent a matrix as a sequence of sequences, then zip can do the job:
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))
我以为你永远也不会问这种问题。如果你把矩阵当做序列的序列的话,那么zip就可以完成这个任务:
要理解这个, 你要先搞清楚 f(*m) 和 apply(f, m) 是一样的。这是基于一个古老的 Lisp 的问题, 答案就是这个和 map(None,*m) 等价的东西, 不过用 zip 的这段程序甚至更短一点。 你可能会想这个只不过对 Letterman's Stupid Programmer's Tricks 的出现有点用而已, 但是有一天, 我遇到了这个问题: 提供一个数据库行的列表, 每一行都是一个排好序了的值的列表, 要你找出这么一个列表, 他里面的值在每 (翻不出来了啊, 这一句, 哪位兄弟来帮一把啊), 于是我这么写下:
1 possible_values = map(unique, zip(*db))