如何在Python中提高循环效率? [英] How can I make the efficent for loop in Python?

查看:88
本文介绍了如何在Python中提高循环效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用python编写csv文件,并且有四个级别的嵌套对象.喜欢

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

我需要这样显示csv

I need to show the csv like this

StudentNameStudentClass SubjectNameSubjectDate SubjectBookNAmeSubjectBookpage

我正在使用类似循环

Just example not actual code

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

如果我有所有子对象,这很好.

This works fine if i have all child objects.

但是当我没有书或科目时,循环将不起作用.

But when i have no books or subjects then loop does not work.

我不想使用很多if else有什么方法可以有效地编写那些循环,如果在for循环中没有行则系统可以工作

I don't want to use many if else is there any way to write those loops efficently that if there are no rows in for loop then system works

推荐答案

假设在没有主题的情况下s.subjectsNone或其他False值,对于书籍同样如此

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)

一般来说,你可以写

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) 

<condition>在哪里有意义?

这篇关于如何在Python中提高循环效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆