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
热门推荐
10 新年稳重的祝福语简短
11 男生打球祝福语简短霸气
12 姐妹分手了祝福语简短
13 参加儿子大学祝福语简短
14 老爸生日暴富祝福语简短
15 新年过后奋斗祝福语简短
16 学生开心成语祝福语简短
17 婚庆花篮祝福语简短大气
18 舅妈生日红包祝福语简短