返回::Python 罕见问题集

::-- huangyi [2006-04-22 16:08:15]

::-- ZoomQuiet [2005-09-06 04:10:30]

::-- WeiZhong [2006-04-24 16:45:30]

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 的问题, 答案等价于 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))