python - 为什么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 循环中存在相同的表达式时会忽略它?如果我在这里遗漏了什么,请随时纠正我。
解决方案
您的理解是正确的:“空字符串是所有字符串的子集”
但是现在让我们看看当我们使用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
str
和list
object 都有,__iter__
所以方法被调用而不是__getitem__
. (__iter__
优先于__getitem__
)
推荐阅读
- smartsheet-api - 是否可以使用 Smartsheet Python SDK 创建 MULTI_PICKLIST?
- javascript - 选择完全清理文件时,Jetbrains Rider 不清理 JavaScript 文件
- r - read.csv / read_csv 删除值
- spring-boot - Spring Java Config DI 定义和 JpaRepository 的(“具体接口”)
- python - 查找所有子字符串和时间限制超出错误
- html - 隐藏滑块图像而不删除
- python - R Vif Function 的类似python函数
- kubernetes - GKE 上的 Istio 是否为相互 TLS 的每个服务创建不同的服务帐户
- java - 如何计算构建哈希表所需的最大/最小探针数
- google-cloud-platform - 需要澄清“授权域”对 OAuth 同意屏幕的作用