Skip to main content
 首页 » 编程设计

python之迭代类对象列表之'pythonic' 方式

2025年05月04日9del

我有一个包含类对象的列表 test_cases。每个对象都有一个名为 ident 的属性。 我想遍历列表中的所有对象并在 ident

下做一些有值(value)的事情

这是我的代码:

class TestCase: 
    def __init__(self, title, ident, description): 
        self.title = title 
        self.ident = ident 
        self.description = description 
 
test_cases = [] 
test_cases.append(TestCase(**tc_dict)) 
 
i = 0 
while i != len(test_cases): 
    print(test_cases[i].ident) 
    i += 1 

它工作正常,但我想问的是,是否有更“pythonic”的方式来做到这一点。

请您参考如下方法:

使用 for 循环直接遍历对象(而不是遍历它们的索引):

for test_case in test_cases: 
    print test_case.ident 

这是通用的方式,当你想遍历对象时应该在 99% 的情况下使用。它在这里完美运行,可能是理想的解决方案。

如果你确实需要索引,你应该使用 enumerate() :

for index, test_case in enumerate(test_cases): 
    print index, test_case.ident 

它仍在遍历对象,但它同时从 enumerate 接收它们的索引。


在您的特定用例中,还有另一种选择。如果您有很多 对象,一个一个地打印出来可能会很慢(调用print 是相当昂贵的)。如果性能成为问题,您可以使用 str.join预先加入值,然后将其全部打印出来:

print '\n'.join(tc.ident for tc in test_cases) 

我个人比较推荐第一种方法,只有当你需要打印很多东西,而且肉眼确实能看到性能问题时,才会引用后者。