Python len()函数

原文: https://thepythonguru.com/python-builtin-functions/len/


于 2020 年 1 月 7 日更新


len()函数计算对象中的项目数。

其语法如下:

  1. len(obj) -> length
参数 描述
obj obj可以是字符串,列表,字典,元组等。

这是一个例子:

  1. >>>
  2. >>> len([1, 2, 3, 4, 5]) # length of list
  3. 5
  4. >>>
  5. >>> print(len({"spande", "club", "diamond", "heart"})) # length of set
  6. 4
  7. >>>
  8. >>> print(len(("alpha", "beta", "gamma"))) # length of tuple
  9. 3
  10. >>>
  11. >>> print(len({ "mango": 10, "apple": 40, "plum": 16 })) # length of dictionary
  12. 3

试试看:

  1. # length of list
  2. print(len([1, 2, 3, 4, 5]))
  3. # length of set
  4. print(len({"spande", "club", "diamond", "heart"}))
  5. # length of tuple
  6. print(len(("alpha", "beta", "gamma")))
  7. # length of dictionary
  8. print(len({ "mango": 10, "apple": 40, "plum": 16 }))

具有讽刺意味的是,len()函数不适用于生成器。 尝试在生成器对象上调用len()将导致TypeError异常。

  1. >>>
  2. >>> def gen_func():
  3. ... for i in range(5):
  4. ... yield i
  5. ...
  6. >>>
  7. >>>
  8. >>> len(gen_func())
  9. Traceback (most recent call last):
  10. File "<stdin>", line 1, in <module>
  11. TypeError: object of type 'generator' has no len()
  12. >>>

试一试:

  1. def gen_func():
  2. for i in range(5):
  3. yield i
  4. print(len(gen_func()))

len()与用户定义的对象


要在用户定义的对象上使用len(),您将必须实现__len__()方法。

  1. >>>
  2. >>> class Stack:
  3. ...
  4. ... def __init__(self):
  5. ... self._stack = []
  6. ...
  7. ... def push(self, item):
  8. ... self._stack.append(item)
  9. ...
  10. ... def pop(self):
  11. ... self._stack.pop()
  12. ...
  13. ... def __len__(self):
  14. ... return len(self._stack)
  15. ...
  16. >>>
  17. >>> s = Stack()
  18. >>>
  19. >>> len(s)
  20. 0
  21. >>>
  22. >>> s.push(2)
  23. >>> s.push(5)
  24. >>> s.push(9)
  25. >>> s.push(12)
  26. >>>
  27. >>> len(s)
  28. 4
  29. >>>

试一试:

  1. class Stack:
  2. def __init__(self):
  3. self._stack = []
  4. def push(self, item):
  5. self._stack.append(item)
  6. def pop(self):
  7. self._stack.pop()
  8. def __len__(self):
  9. return len(self._stack)
  10. s = Stack()
  11. print(len(s))
  12. s.push(2)
  13. s.push(5)
  14. s.push(9)
  15. s.push(12)
  16. print(len(s))