首页 > 解决方案 > 为什么for循环在python中退出“”(空字符串)?

问题描述

为了解释我的查询,我在下面有一个简单的代码片段,然后是我的问题。

def count_vowels(s):
    num_vowels = 0
    for char in s:
        if char in 'aeiouAEIOU':
             num_vowels = num_vowels + 1
    return num_vowels

print(count_vowels(""))
print("" in "aeiouAEIOU")

给出一个输出

0 
True

我的疑问:

为什么表达式""返回一个空字符串True

"" in "aeiouAEIOU"

但是当它与 for 循环一起出现时它会跳过吗?

for char in s:  

我的理解是空字符串是所有字符串的子集,那么为什么在 for 循环中存在相同的表达式时会忽略它?如果我在这里遗漏了什么,请随时纠正我。

标签: pythonpython-3.x

解决方案


您的理解是正确的:“空字符串是所有字符串的子集”

但是现在让我们看看当我们使用for诸如字符串之类的序列类型时会发生什么。假设我们有:

lst = [1, 2, 3, 4, 5]

for i in lst:
    print(i ** 2)

你可以认为它变成了:

index = 0
while True:
    try:
        i = lst.__getitem__(index)
    except IndexError:
        break
    print(i ** 2)
    index += 1

在您的示例中,当它尝试获取第一项时,它会引发异常并跳出循环。所以它甚至不会进入For循环。

我说“只是想想”,因为在 for 循环中,iter()在对象(此处lst)上被调用,并且此内置函数将从对象中获取迭代器。为了发生这种情况,对象应该实现可迭代协议,__iter__或者它必须支持序列协议(the __getitem__()))。

lst = [1, 2, 3, 4, 5]
it = iter(lst)
try:
    while i := next(it):
        print(i ** 2)
except StopIteration:
    pass

strlistobject 都有,__iter__所以方法被调用而不是__getitem__. (__iter__优先于__getitem__


推荐阅读