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