简体   繁体   English

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

[英]Iterate over list of class objects - 'pythonic' way

I have a list test_cases with class objects.我有一个带有类对象的列表test_cases Every object has an attribute called ident .每个对象都有一个名为ident的属性。 I want to iterate over all objects from list and do something with value under ident我想遍历列表中的所有对象并在ident下做一些具有价值的事情

This is my code:这是我的代码:

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

It works fine, but what I want to ask, if there is a more 'pythonic' way to do that.它工作正常,但我想问的是,是否有更“pythonic”的方式来做到这一点。

Use a for loop to iterate over the objects directly (as opposed to iterating over their indexes):使用for循环直接迭代对象(而不是迭代它们的索引):

for test_case in test_cases:
    print test_case.ident

This is the generic way, and should be used 99% of the time when you want to loop over objects.这是通用方式,当您想要循环对象时,应该在 99% 的情况下使用它。 It works perfectly here and is probably the ideal solution.它在这里完美运行,可能是理想的解决方案。

If you ever do need the indexes, you should use enumerate() :如果您确实需要索引,则应该使用enumerate()

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

It's still looping over the objects, but it's simultaneously receiving their indexes from enumerate .它仍然在对象上循环,但同时从enumerate接收它们的索引。


In your particular use case , there is another option though.在您的特定用例中,还有另一种选择。 If you have a lot of objects, it might be slow to print them out one by one (calling print is rather expensive).如果您有很多对象,将它们一个一个打印出来可能会很慢(调用print相当昂贵)。 If performance turns out to be an issue, you can use str.join to join the values beforehand, and then print it all out once:如果性能成为问题,您可以使用str.join预先连接值,然后将其全部打印出来:

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

I personally recommend the first method, and would only refer to the latter when you need to print out a lot of stuff and actually can see the performance issue with your naked eye.我个人推荐第一种方法,只有当你需要打印出很多东西并且实际上可以用肉眼看到性能问题时才会使用后一种方法。

First, you can replace your while loop by a for loop首先,您可以用 for 循环替换 while 循环

for i in range(len(test_cases)):
    print test_cases[i].indent

However, looping over an index and accessing an element by using that index is often a code smell in python.但是,循环遍历索引并使用该索引访问元素通常是 Python 中的代码异味。 Better would simply be to loop over the elements更好的是简单地循环遍历元素

for test_case in test_cases:
    print test_case.indent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM