开发者

Python: list of lists anf HTML table help

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>'


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>'


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.


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>'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜