tags:

views:

43

answers:

3

I'm having trouble appending the values from a list of lists into a html table, for example my list if lists contains:

food_list = [['A','B'], ['Apple','banana'], ['Fruit','Fruit']]

How would i append each value into a correspondong HTML table? So the code looks like:

<table>
<tr><td>A</td><td>Apple</td><td>Fruit</td></tr>
<tr><td>B</td><td>Banana</td><td>Fruit</td></tr>
</table>

the closest i could get was with the code below, but i get a list index out of range error.

print '<table>'
for i in food_list:
    print '<tr>'
    print '<tr><td>'+i[0]+'</td><td>'+i[1]+'</td><td>'+i[2]+'</td></tr>'
    print '</tr>'
print' </table>'
A: 
print '<table>'
for i in food_list:
    print '<tr>'
    print '<tr><td>'+i[0]+'</td><td>'+i[1]+'</td></th>'
    print '</tr>'
print' </table>'
jsbueno
+3  A: 

I would do it like this;

# Example data.
raw_rows = [["A", "B"], ["Apple", "Banana"], ["Fruit", "Fruit"]]
# "zips" together several sublists, so it becomes [("A", "Apple", "Fruit"), ...].
rows = zip(*raw_rows) 

html = "<table>"
for row in rows:
   html += "<tr>"
   # Make <tr>-pairs, then join them.
   html += "\n".join(map(lambda x: "<td>" + x + "</td>", row)) 
   html += "</tr>"

html += "</table>"

Maybe not the quickest version but it wraps up the rows into tuples, then we can just iterate over them and concatenate them.

Skurmedel
+2  A: 

I think you're looking for this:

print '<table>'
for i in zip(*food_list):
    print '<tr>'
    print '<td>'+i[0]+'</td><td>'+i[1]+'</td><td>'+i[2]+'</td>'
    print '</tr>'
print' </table>'
WoLpH
Thank you very much :)
Harpal