迭代类对象列表-';pythonic';方式

迭代类对象列表-';pythonic';方式,python,Python,我有一个带有类对象的测试用例列表。每个对象都有一个名为ident的属性。 我想迭代列表中的所有对象,并在ident 这是我的代码: class TestCase: def __init__(self, title, ident, description): self.title = title self.ident = ident self.description = description test_cases = [] test_ca

我有一个带有类对象的测试用例列表。每个对象都有一个名为
ident
的属性。 我想迭代列表中的所有对象,并在
ident

这是我的代码:

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
循环直接迭代对象(而不是迭代对象的索引):

这是一种通用的方法,当您想要在对象上循环时,应该在99%的时间使用这种方法。它在这里非常有效,可能是理想的解决方案

如果确实需要索引,则应使用:

它仍然在对象上循环,但同时从
enumerate
接收它们的索引


在您的特定用例中,还有另一个选项。如果您有很多对象,则逐个打印它们可能会很慢(调用
print
的成本相当高)。如果性能出现问题,您可以使用预先加入值,然后将其全部打印一次:

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

我个人推荐第一种方法,并且只有当您需要打印大量内容,并且实际上可以用肉眼看到性能问题时,才会使用后者。

首先,您可以用for循环替换while循环

for i in range(len(test_cases)):
    print test_cases[i].indent
然而,在python中,循环索引并使用该索引访问元素通常是一种代码味道。最好是在元素上循环

for test_case in test_cases:
    print test_case.indent

你能提供测试用例值吗??(列表的一个例子)奇迹般地,我找不到关于这个的过去的问题;尽管如此,我们还是对其进行了详细的讨论,例如,PyCon 2013年的演讲。很好,Markus,我想在打印“\n”中添加一个检查hasattr(object,'attribute')。join(测试用例中tc的tc.ident)将是安全的。您可能不应该在列表中随机添加不同类型的对象。OP的示例具有
TestCase
类,因此如果您将不与
TestCase
一起回避的对象混合在一起,则很可能会引发错误。
for i in range(len(test_cases)):
    print test_cases[i].indent
for test_case in test_cases:
    print test_case.indent