How can I make the efficent for loop in Python?

后端 未结 3 372
自闭症患者
自闭症患者 2021-01-29 16:34

I am writing the csv file in python and there are four levels of nested objects. like

I need to show the csv like this

StudentName, StudentCla

相关标签:
3条回答
  • 2021-01-29 17:33

    You should Initialize s.subjects and subject.books with empty lists. That way you won't get an error when trying to iterate them here or on other places in your code.

    0 讨论(0)
  • 2021-01-29 17:33

    Initialize your student.subjects and subject.books with [], and then it'll work. Just as what @user714965 said.

    or, use list-comprehension:

    for s in [stu if stu.has_key(subjects) for stu in students]:
        for subject in [subj if subj.has_key(books) for subj in s.subjects]:
             lists= [(s.name, s.class, subject.name, book.name) for book in subject.books]
                  print r'\n'.join(r','join(lists))
    

    or

    if your loop is not very deep,try something like this:

    fn= s.has_key('subjects') and (lambda s: /do sth. with s/ ) or (lambda s: /do sth. else with s/)
    

    in your loop, use the fn like this,

    [fn(s) for s in students ]
    
    0 讨论(0)
  • 2021-01-29 17:38

    Assuming s.subjects is None or some other False value when there are no subjects, and likewise for books

    for s in students:
        for subject in s.subjects or []:
            for book in subject.books or []:
                writer.writerow(s.name, s.class, subject.name, book.name)
    

    More generally, you can write

    for s in students:
        for subject in s.subjects if <condition> else []:
            for book in subject.books if <condition> else []:
                writer.writerow(s.name, s.class, subject.name, book.name) 
    

    Where <condition> is whatever expression makes sense

    0 讨论(0)
提交回复
热议问题