0

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>'
1
  • 1
    By the way, it would probably make more sense if you could structure the list differently in the first place, like [['A','Apple','Fruit'],['B','banana','Fruit']]. That way each row logically corresponds to one "thing" (i.e. a row for the apple, a row for the banana, etc.), plus the code you were trying to use would have worked. Commented Jul 11, 2010 at 21:42

3 Answers 3

3

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>'
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

The table has two elements, so you would use 0 and 1 as indexes. Here is your example rewritten:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.