如何使用Python打印HTML文件中的嵌套列表?

问题描述 投票:0回答:3

我正在尝试使用 python 编写 HTML 文件,并且我想在 .html 中打印嵌套列表。

我已经写了这个,但我不知道如何做好。

words = [['Hi'], ['From'], ['Python']]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<h1>---------------------------</h1>')

    for i in range(len(words)):
        myFile.write('<tr><td>'(words[i])'</td></tr>')


    myFile.write('</body>')
    myFile.write('</html>')

在 .html 中,我想以类似的格式打印表格中的嵌套列表:

<body>
    <table>
        <tr>
            <td>Hi</td>
        </tr>
        <tr>
            <td>From</td>
        </tr>
        <tr>
            <td>Python</td>
        </tr>
    </table>
</body>
python python-3.x list for-loop
3个回答
2
投票
words = [['Hi'], ['From'], ['Python']]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<h1>---------------------------</h1>')

    
    # 2-depth string data to 1-depth 
    words = [word_str for inner in words for word_str in inner] 
    
    # use fstring to build string
    <table>
    for word in words:
        myFile.write(f'<tr><td>{word}</td></tr>') 
    </table>


    myFile.write('</body>')
    myFile.write('</html>')

我尝试编辑已接受的答案,但我没空,但你只需添加

<table> and </table>


1
投票

这个怎么样?

words = [['Hi'], ['From'], ['Python']]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<h1>---------------------------</h1>')

    
    # 2-depth string data to 1-depth 
    words = [word_str for inner in words for word_str in inner] 
    
    # use fstring to build string
    for word in words:
        myFile.write(f'<tr><td>{word}</td></tr>')  


    myFile.write('</body>')
    myFile.write('</html>')

0
投票

您可以使用 tabulate 为此

words = [['Hi'], ['From'], ['Python']]
print(tabulate(words, tablefmt="html"))

输出:

<table>
<tbody>
<tr><td>Hi    </td></tr>
<tr><td>From  </td></tr>
<tr><td>Python</td></tr>
</tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.