Mike Orr avatar Mike Orr committed 1dd58fa

Add transpose() helper.

Comments (0)

Files changed (1)

webhelpers/containers.py

     else:
         raise ValueError("arg ``direction`` must start with 'H' or 'V'")
 
+def transpose(array):
+    """Turn a list of lists sideways, making columns into rows and vice-versa.
+
+    The result is undefined if the array is not rectangular; i.e., if
+    ``len(array[n]) != len(array[0])``.  You may get an ``IndexError`` or
+    missing items.
+
+    Picture the first example as:
+       A B C    =>    A D
+       D E F          B E
+                      C F
+
+    The source array is row-major (``array[n]`` is a row, ``array[n][0]`` is
+    the first element of the row), which is good for an HTML table which is
+    also row-major (columns within rows).  The result is column-major
+    (``array[n]`` is a column, ``array[n][0]`` is the first row in the column),
+    which is good for a group of <div> columns with <br /> between rows.
+
+    >>> transpose([["A", "B", "C"], ["D", "E", "F"]])
+    [['A', 'D'], ['B', 'E'], ['C', 'F']]
+    >>> transpose([["A", "B"], ["C", "D"], ["E", "F"]])
+    [['A', 'C', 'E'], ['B', 'D', 'F']]
+    >>> transpose([])
+    []
+    """
+    if not array:
+        return []
+    ret = []
+    for c in range(len(array[0])):
+        col = [row[c] for row in array]
+        ret.append(col)
+    return ret
+        
+
 
 if __name__ == "__main__":
     import doctest
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.