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

更新於:30-7 月 - 2019

743 次瀏覽

開創您的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.