transpose(m): transposes a 2D matrix, made of tuples or lists of tuples or lists, keeping their type. >>> transpose([]) Traceback (most recent call last): ... IndexError: list index out of range >>> transpose([[]]) [] >>> transpose([1,2,3]) Traceback (most rece
(m)
| 53 | |
| 54 | |
| 55 | def transpose(m): |
| 56 | """transpose(m): transposes a 2D matrix, made of tuples or lists of tuples or lists, |
| 57 | keeping their type. |
| 58 | |
| 59 | >>> transpose([]) |
| 60 | Traceback (most recent call last): |
| 61 | ... |
| 62 | IndexError: list index out of range |
| 63 | >>> transpose([[]]) |
| 64 | [] |
| 65 | >>> transpose([1,2,3]) |
| 66 | Traceback (most recent call last): |
| 67 | ... |
| 68 | TypeError: zip argument #1 must support iteration |
| 69 | >>> transpose([[1,2,3]]) |
| 70 | [[1], [2], [3]] |
| 71 | >>> transpose( [[2, 2, 2], [2, 2, 2]] ) |
| 72 | [[2, 2], [2, 2], [2, 2]] |
| 73 | >>> transpose( [(2, 2, 2), (2, 2, 2)] ) |
| 74 | [(2, 2), (2, 2), (2, 2)] |
| 75 | >>> transpose( ([2, 2, 2], [2, 2, 2]) ) |
| 76 | ([2, 2], [2, 2], [2, 2]) |
| 77 | >>> transpose( ((2, 2, 2), (2, 2, 2)) ) |
| 78 | ((2, 2), (2, 2), (2, 2)) |
| 79 | >>> t = [[[1], [2]], [[3], [4]], [[5], [6]]] |
| 80 | >>> transpose(t) |
| 81 | [[[1], [3], [5]], [[2], [4], [6]]] |
| 82 | """ |
| 83 | if isinstance(m, list): |
| 84 | if isinstance(m[0], list): |
| 85 | return map(list, zip(*m)) |
| 86 | else: |
| 87 | return zip(*m) # faster |
| 88 | else: |
| 89 | if isinstance(m[0], list): |
| 90 | return tuple(map(list, zip(*m))) |
| 91 | else: |
| 92 | return tuple( zip(*m) ) |
| 93 | |
| 94 | if __name__ == "__main__": |
| 95 | import doctest |