【问题标题】:Checking if iterable is empty before while loop在while循环之前检查iterable是否为空
【发布时间】:2021-02-25 21:51:56
【问题描述】:

最近我不得不制作动态变化的列表,我在主循环中迭代。但它们最初是空的,有时可能是空的。 这里有两种情况:

# The first one
iterable = []
if iterable:
    for i in iterable:
        # do sth

# and the second
iterable = []
for i in iterable:
    # do sth

我想知道这两种情况的性能是否存在一些差异,或者 empty 检查已经在 for 循环中实现了?

【问题讨论】:

  • 您可以自己尝试一下。提示:for 句柄和空序列就好了。

标签: python-3.x performance for-loop iterable is-empty


【解决方案1】:

当你迭代一个 define 列表变量时,你没有遇到任何问题,看看:

>>> iterable=[]
>>> for x in iterable:
    print(x)

>>> 

空检查会自动为您完成。

因此,最好在您的问题中使用 second 代码 sn-p,因为没有 redundant if iterable: 代码行。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2016-11-19
    • 2014-09-04
    • 2023-03-06
    相关资源
    最近更新 更多