Python 中自定义 len() 函数
我们来看看如何在 Python 中实现自定义 len() 函数。请先按照以下步骤自己尝试一下。
步骤
从用户字符串/列表/元组获取迭代器。
定义一个自定义名称的函数,通过传递迭代器来调用它。
- 将计数初始化为 0。
- 运行一个循环,直到达到结尾。
- 将计数增加 1
- 返回计数。
示例
## function to calculate lenght of the iterator
def length(iterator):
## initializing the count to 0
count = 0
## iterating through the iterator
for item in iterator:
## incrementing count
count += 1
## returning the length of the iterator
return count
if __name__ == "__main__":
## getting input from the user
iterator = input("Enter a string:- ")
## invoking the length function with 'iterator'
print(f"Length of {iterator} is {length(iterator)}")运行上述程序,您将获得以下结果。
输出
Enter a string:- tutorialspoint Length of tutorialspoint is 14
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP