如何以表格形式打印多个对象的参数? [英] How do I print parameters of multiple objects in table form?

查看:75
本文介绍了如何以表格形式打印多个对象的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我想在一个漂亮的表中打印每个对象的参数.

I have a list of objects and I want to print the parameters of each in a nice table.

我的代码在这里:

class item(object):
    def __init__(self, thing, owner, color):
        self.thing = thing
        self.owner = owner
        self.color = color

bin = []
bin.append(item('shirt', 'John', 'red'))
bin.append(item('skirt', 'Jane', 'blue'))    

## Need help here
## Can't figure this out

print '%-10s %-10s %-10s' % (bin[0].thing, bin[0].owner, bin[0].color)

我想要得到的输出是

shirt       skirt
John        Jane
red         blue

推荐答案

for attr in ('thing', 'owner', 'color'):
    for item in bin:
        print '%-10s'%getattr(item, attr),
    print

使用列表理解更为紧凑

for atts in ('thing', 'owner', 'color'):
    print ' '.join('%-10s'%getattr(item, attr) for item in bin)

这篇关于如何以表格形式打印多个对象的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆