遍历类对象列表-“pythonic”方式

2024-04-16 20:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有类对象的列表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

它的工作很好,但我想问的是,是否有更多的'Python'的方式来做到这一点。


Tags: 对象代码testself列表属性titleinit
2条回答

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

for test_case in test_cases:
    print test_case.ident

这是一种通用的方法,当您希望循环对象时,99%的时间都应该使用这种方法。它在这里工作得很好,可能是理想的解决方案。

如果确实需要索引,则应使用^{}

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

它仍在对象上循环,但同时从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

相关问题 更多 >