Using nested lists and tables

Peter Otten __peter__ at web.de
Thu Oct 28 11:27:56 EDT 2010


Zeynel wrote:

> Thank you this is great; but I don't know how to modify this code so
> that when the user types the string 's' on the form in the app he sees
> what he is typing. So, this will be in GAE. 

I've no idea what GAE is. In general the more precise your question is the 
better the answers tend to be. Don't make your readers guess. 

>>>> for row in range(max(len(c) for c in columns)):
>> ...     print " | ".join(c[row] if len(c) > row else " "*len(c[0]) for c
>> in columns)
> 
> What is "c" here?
 
Sorry, I was trying to do too much in a single line.

result = [c for c in columns]

is a way to iterate over a list. It is roughly equivalent to

result = []
for c in columns:
    result.append(c)

Then, if columns is a list of lists of strings 'c' is a list of strings. 
You normally don't just append the values as you iterate over them, you do 
some calculation. For example

column_lengths = [len(c) for c in columns]

would produce a list containing the individual lengths of the columns.

A simpler and more readable version of the above snippet from the 
interactive python session is

columns = [
    ['abc', 'abc', 'abc'],
    ['xy', 'xy'],
    ["that's all, folks"]]

column_lengths = [len(column) for column in columns]
num_rows = max(column_lengths)
for row_index in range(num_rows):
    row_data = []
    for column in columns:
        # check if there is a row_index-th row in the
        # current column
        if len(column) > row_index:
            value = column[row_index]
        else:
            # there is no row_index-th row for this
            # column; use the appropriate number of
            # spaces instead
            value = " " * len(column[0])
        row_data.append(value)
    print " | ".join(row_data)







More information about the Python-list mailing list