列表 (list) 为空是指列表中没有元素,是一个空集合。在 Python 中检查列表有没有元素有多种方法,本文介绍一下三种方法:
- 空集合比较
- 检查列表长度
- if not (性能最好)
以上方法的使用示例如下所示。
# 定义一个列表 a_list = list() # 空集合比较 if a_list == []: pass # 列表为空 # 检查列表长度是否为0 if len(a_list) == 0: pass # 列表为空 # if not if not a_list: pass # 列表为空
这三种方法的性能有差异吗?下面使用 timeit 库进行测试,测试代码如下:
import timeit setup = """ my_list = list() """ method_1_test_code = """ if len(my_list) == 0: pass """ method_2_test_code = """ if my_list == []: pass """ method_3_test_code = """ if not my_list: pass """ method_1_taking_time = timeit.timeit(stmt=method_1_test_code, setup=setup, number=100) method_2_taking_time = timeit.timeit(stmt=method_2_test_code, setup=setup, number=100) method_3_taking_time = timeit.timeit(stmt=method_3_test_code, setup=setup, number=100) print('空集合比较方法耗时: ' + str(method_1_taking_time)) print('检查列表长度方法耗时: ' + str(method_2_taking_time)) print('if not方法耗时: ' + str(method_3_taking_time))
测试结果:
空集合比较方法耗时: 8.800008799880743e-06 检查列表长度方法耗时: 6.599992047995329e-06 if not方法耗时: 4.400033503770828e-06
从测试结果可以看出 if not
方法性能最好。
有关 Python 代码运行速度的测试方法请参见:如何测试 Python 代码的速度 - datetime, timeit