【问题标题】:Create HTML table from 2 lists in python 3从 python 3 中的 2 个列表创建 HTML 表
【发布时间】:2020-09-15 03:24:37
【问题描述】:

我已经查看了here,但解决方案对我来说仍然无效...... 我有2 lists

list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']

list2 = ['src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7)',
         'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)']

list1 带有HTML 表的column names

第二个list2 带有table data

如何从这两个列表中生成HTML table,以便第一个列表用于column names,第二个作为table data(逐行)

结果应该是:

src_table          |  error_response_code  | error_count  | max_dt                  |
src_periods_43200  |  404                  | 21           | 2020-5-26    21:10:7    |
src_periods_43200  |  404                  | 19           | 2020-5-25    21:10:7    |

非常感谢

【问题讨论】:

    标签: python html html-table


    【解决方案1】:

    应该这样做

    import pandas as pd
    import datetime
    
    list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']
    
    list2 = [
        'src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7),
        'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)
    ]
    
    
    index_break = len(list1)
    if len(list2) % index_break != 0:
        raise Exception('Not enough data.')
    
    staged_list = []
    current_list = []
    
    for idx in range(0, len(list2)):
        current_list.append(list2[idx])
    
        if len(current_list) == index_break:
            staged_list.append(current_list.copy())
            current_list = []
    
    df = pd.DataFrame(data=staged_list, columns=list1)
    
    print(df.to_html())
    

    【讨论】:

    【解决方案2】:

    您可以轻松地为此编写函数 比如:

    import datetime
    
    list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']
    
    list2 = ['src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7), 'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)]
    
    print('<table>')
    print('<thead><tr>')
    for li in list1:
        print(f'<th>{li}</th>')
    print('</tr></thead>')
    print('<tbody>')
    for i in range(0, int(len(list2)/4)):
        print('<tr>')
        print(f'<td>{list2[4*i+0]}</td>')
        print(f'<td>{list2[4*i+1]}</td>')
        print(f'<td>{list2[4*i+2]}</td>')
        print(f'<td>{list2[4*i+3]}</td>')
        print('</tr>')
    print('</tbody>')
    print('</table>')
    

    【讨论】:

    • 如果不想打印,可以制作str+= ....,然后发送到某处
    猜你喜欢
    • 2021-08-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多