python - 如何转换为while循环
问题描述
我写了这段代码。这就像 len() 函数。
def length_itr_for(list):
total = 0
for i in list:
total += 1
return total
print length_itr_for([1,2,3,4,5,6,7,8])
输出是;8. 因为在这个列表中,有 8 个值。所以 len 在这个列表中是 8。
但我不知道如何用while循环编写这段代码?
while list[i]: etc... 我虽然做了一些事情,但我不知道我应该在这里写什么。
编辑:实际上我也试过这段代码。但这不是好的代码。刚刚尝试过,但没有奏效。
def length_itr_whl(list):
total = 0
i = 0
while list[i]:
total = total + 1
i = i + 1
return total
print length_itr_whl([1,2,3,4,5])
解决方案
您可以编写一个函数来测试索引是否在列表的范围内:
def validIndex(l, i):
try:
_ = l[i]
except IndexError:
return False
return True
然后你可以在你的循环中使用它:
def length_itr_whl(list):
total = 0
index = 0
while validIndex(list, index):
total += 1
index += 1
return total
您还可以while True:
在循环中使用并捕获索引错误。
def length_itr_whl(list):
total = 0
index = 0
try:
while True:
_ = list[index]
total += 1
index += 1
except IndexError:
pass
return total
推荐阅读
- javascript - V12 Discord.js 从消息反应中检索 user.id
- react-native - React Native:Java 堆空间
- javascript - 在为按钮处理 Discord 的“interactionCreate”事件时,每个按钮都有单独的文件并与各种命令文件通信?
- windows - 制作macOS版windows源码
- r - 为什么我的 R 与 rowSums 发生变异不起作用(错误:`mutate()` 输入 `..2` 有问题。x 'x' 必须是数字 ℹ 输入 `..2` 是 `rowSums(.)`。) ?
- javascript - 在 MongoDB 中解析结果
- python - 检查一个数是否为素数
- python - 使用 Shopify Python API 获取公共 URL 以存储徽标
- c - 从 Windows 95 向后兼容
- python - 为什么 numpy arange 数字在步进十万分之一时没有按预期步进?