【问题标题】:Python customize List output [closed]Python自定义列表输出[关闭]
【发布时间】:2017-06-09 20:47:49
【问题描述】:

我打开这个帖子是因为我想知道如何以及是否可以像这样自定义列表输出:

1       2.33     KG
2       3.0      KG
3       (empty)   3
x       222      KG
y       233.4    KG
y       112      %
z       222      KG
w       9.98     KG
a       3224     KG
...     ....    ....

有人可以告诉我吗?

【问题讨论】:

标签: python


【解决方案1】:

根据您要做什么,您可以尝试pandas,它非常适合处理和打印二维数组,或者string formattingthis answer 中讨论

【讨论】:

    【解决方案2】:

    请出示您的代码。但我假设您想知道如何执行您在上面输入的内容。

    最好将变量放在元组列表中,如下所示:

    your_tuple_list_name = [(1, 2.33, 'KG'), (2, 3.0, 'KG'), (3, '(empty)', 'KG'), ('x', 222, 'KG'), ('y', 233.4, 'KG'), ('y', 112, '%'), ('z', 222, 'KG'), ('w', 9.98, 'KG'), ('a', 3224, 'KG'), ('.', '....', '..'), (add other tuples here)]`
    

    如果您想向元组列表中添加更多项目,只需按照以下格式添加它们:

    (first_column, second_column, third_column)

    然后方法是这样的:

    def formatted_printing(your_tuple_list):
        space = ' '
        for n in range(len(your_tuple_list)):
            number = 8 - len(str((your_tuple_list[n][1])))
            print("{:>}    {:<}{}{:<}".format(your_tuple_list[n][0], your_tuple_list[n][1], (space * number), your_tuple_list[n][2]))
    
    
    formatted_printing(your_tuple_list_name)
    

    输出如下:

    1    2.33    KG
    2    3.0     KG
    3    (empty) KG
    x    222     KG
    y    233.4   KG
    y    112     %
    z    222     KG
    w    9.98    KG
    a    3224    KG
    .    ....    ....
    

    【讨论】:

    • 非常感谢,对我帮助很大^_^
    【解决方案3】:

    尝试在列表中构造一个列表。 像 [[1 ,2.33 ,KG],[2, 3.0,KG],[3,' ',3]] 然后,您可以通过遍历列表来访问每个元素。

    <table>    
    for i in [[1 ,2.33 ,KG],[2, 3.0,KG],[3,' ',3]]:
        <tr>
        for j in i:
           <td>j</td> 
        </tr>
     </table>
    

    【讨论】:

    • 大家好,我能够使用 lobfil 的解决方案解决我的问题。再次感谢大家^_^
    • @Soichiro 如果发现任何作者的答案有用,请在答案附近打勾。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2018-04-15
    相关资源
    最近更新 更多