我在使用python格式化html中的表格时遇到了困难。我正在使用以前信息中的for循环,并且前两列已经格式化,但我很难将某些值放在正确的位置。
for c in sorted(max_films):
print "<tr><th>"
print c
print "<td>"
print max_films[c]
print "</td></tr>"
for c in max_list1:
print "<tr><th>"
print "<td>"
print c
print "</td></tr>"
这是它正在制作的表格:
电影(完美风暴 - 300)应该在第三列而不是第二列之间对齐。我该如何解决这个问题?
完整的HTML代码:
print "Content-Type: text/html"
print ""
print "<html>"
print "<body>"
print "<table border=1>"
print "<tr>"
print "<th><font color=black>Year</font></th>"
print "<th><font color=blue>Highest Grossing Film</font></th>"
print "<th><font color=red>Most Similar</font></th>"
print "<th><font color=red>2nd Most Similar</font></th>"
print "<th><font color=red>3rd Most Similar</font></th>"
print "<th><font color=red>4th Most Similar</font></th>"
print "</tr>"
for c in sorted(max_films):
print "<tr><th>"
print c
print "<td>"
print max_films[c]
print "</td></tr>"
for c in max_list1:
print "<tr><th>"
print "<td>"
print c
print "</td></tr>"
print "</body>"
print "</html>"
sorted(max_films) = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007']
max_list1 = ['The Perfect Storm', 'Planet of the Apes', 'The Lord of the Rings: The Fellowship of the Ring', 'Spirited Away', 'Collateral', 'Troy', 'The Chronicles of Narnia: The Lion the Witch and the Wardrobe', '300']
答案 0 :(得分:0)
<table>
<tr>
<th>Year</th>
<th>Highest Grossing Film</th>
<th>Most Similar</th>
<th>2nd Most Similar</th>
<th>3rd Most Similar</th>
</tr>
<!-- create rows in a loop -->
<tr>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
</tr>
<!-- loop this ^^ -->
</table>
参见示例:http://jsfiddle.net/n2w5D/
创建表时不能循环遍历列,因为您需要将行的所有表格单元格写入一行。表的结构基于行作为父元素而不是列! 您需要获得每行的数据,以便采用以下方式:
print "<table>"
print "<tr>"
// print your caption row
print "<th> Year </th>"
print "<th> Highest Grossing Film </th>"
print "<th> Most Similar </th>"
print "<th> 2nd Most Similar </th>"
print "<th> 3rd Most Similar </th>"
print "</tr>"
// loop data
for row_data in data:
print "<tr>"
// print data (maybe: row_data[0] == year, row_data[1] == movie name etc.)
for cell_data in row_data:
print "<td>"
print cell_data
print "</td>"
print "</tr>"
print "</table>"
在您发布完整代码后,我认为您不是指列,而是行! 我想这就是你想要的:
for c in sorted(max_films):
print "<tr><td>"
print max_films[c]
print "</td>"
for c in max_list1:
print "<td>"
print c
print "</td></tr>"