::-- 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?

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

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

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

• Page.execute = 0.072s
• getACL = 0.028s
• init = 0.001s