Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查列表是否为空或只是迭代空列表,哪一种优化效果更好?_Python - Fatal编程技术网

Python 检查列表是否为空或只是迭代空列表,哪一种优化效果更好?

Python 检查列表是否为空或只是迭代空列表,哪一种优化效果更好?,python,Python,在使用循环之前是否需要检查列表是否为空 import bpy list = [] if len(list): # is it better to remove this line? for each in list: print(each) 为可读性和清晰性编写代码。在您有理由相信某段代码是代码的瓶颈之前,不要担心优化。我向您保证,检查列表的长度不是代码中的瓶颈。如果列表为空,它将不会执行循环体,TLDR无需检查列表是否为空。当然,这取决于您想做什么。对于其他步骤或

在使用循环之前是否需要检查列表是否为空

import bpy

list = []

if len(list): # is it better to remove this line?
    for each in list:
        print(each)

为可读性和清晰性编写代码。在您有理由相信某段代码是代码的瓶颈之前,不要担心优化。我向您保证,检查列表的长度不是代码中的瓶颈。

如果列表为空,它将不会执行循环体,TLDR无需检查列表是否为空。当然,这取决于您想做什么。对于其他步骤或
else
语句,您需要知道列表是否为空吗?检查列表是否为非空的首选方法是
if list:
。但由于这并不比简单地获得一个列表迭代器便宜,所以您不必费心检查。编写代码以确保可读性和清晰性。在您有理由相信某段代码是代码的瓶颈之前,不要担心优化。我向您保证,检查列表的长度并不是代码中的瓶颈。我认为检查列表的长度可能会对读者起到相反的作用——这表明作者对
for
循环的工作方式没有信心,并怀疑他们可能误解的其他基本内容。