首页 > 解决方案 > 如何使用 python 在 HTML 文件中打印嵌套列表?

问题描述

我正在尝试使用 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>

标签: pythonpython-3.xlistfor-loop

解决方案


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>


推荐阅读