简体   繁体   中英

Iterate over list of class objects - 'pythonic' way

I have a list test_cases with class objects. Every object has an attribute called ident . I want to iterate over all objects from list and do something with value under 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.

Use a for loop to iterate over the objects directly (as opposed to iterating over their indexes):

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. It works perfectly here and is probably the ideal solution.

If you ever do need the indexes, you should use 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 .


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). 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:

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 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. Better would simply be to loop over the elements

for test_case in test_cases:
    print test_case.indent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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