Python中的自定义len()函数
让我们看看如何len()在Python中实现自定义函数。首先使用以下步骤自己尝试。
步骤
从用户字符串/列表/元组获取迭代器。
根据需要定义一个具有自定义名称的函数,然后通过传递迭代器来调用它。
计数增加1
将计数初始化为0。
循环运行直到结束。
返回计数。
示例
## 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:- nhooo Length of nhooo is 14
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿