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

时间:2017-05-26 07:43:25

标签: python python-2.7

我有一个包含类对象的列表test_cases。每个对象都有一个名为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'方法可以做到这一点。

2 个答案:

答案 0 :(得分:5)

使用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)

我个人推荐第一种方法,当你需要打印很多的东西时,我只会参考后者,实际上可以用肉眼看到性能问题。

答案 1 :(得分:1)

首先,您可以通过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