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 教师闺蜜祝福语简短