💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Python `len()`函数 > 原文: [https://thepythonguru.com/python-builtin-functions/len/](https://thepythonguru.com/python-builtin-functions/len/) * * * 于 2020 年 1 月 7 日更新 * * * `len()`函数计算对象中的项目数。 其语法如下: ```py len(obj) -> length ``` | 参数 | 描述 | | --- | --- | | `obj` | `obj`可以是字符串,列表,字典,元组等。 | 这是一个例子: ```py >>> >>> len([1, 2, 3, 4, 5]) # length of list 5 >>> >>> print(len({"spande", "club", "diamond", "heart"})) # length of set 4 >>> >>> print(len(("alpha", "beta", "gamma"))) # length of tuple 3 >>> >>> print(len({ "mango": 10, "apple": 40, "plum": 16 })) # length of dictionary 3 ``` 试试看: ```py # length of list print(len([1, 2, 3, 4, 5])) # length of set print(len({"spande", "club", "diamond", "heart"})) # length of tuple print(len(("alpha", "beta", "gamma"))) # length of dictionary print(len({ "mango": 10, "apple": 40, "plum": 16 })) ``` 具有讽刺意味的是,`len()`函数不适用于生成器。 尝试在生成器对象上调用`len()`将导致`TypeError`异常。 ```py >>> >>> def gen_func(): ... for i in range(5): ... yield i ... >>> >>> >>> len(gen_func()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'generator' has no len() >>> ``` 试一试: ```py def gen_func(): for i in range(5): yield i print(len(gen_func())) ``` ## `len()`与用户定义的对象 * * * 要在用户定义的对象上使用`len()`,您将必须实现`__len__()`方法。 ```py >>> >>> class Stack: ... ... def __init__(self): ... self._stack = [] ... ... def push(self, item): ... self._stack.append(item) ... ... def pop(self): ... self._stack.pop() ... ... def __len__(self): ... return len(self._stack) ... >>> >>> s = Stack() >>> >>> len(s) 0 >>> >>> s.push(2) >>> s.push(5) >>> s.push(9) >>> s.push(12) >>> >>> len(s) 4 >>> ``` 试一试: ```py class Stack: def __init__(self): self._stack = [] def push(self, item): self._stack.append(item) def pop(self): self._stack.pop() def __len__(self): return len(self._stack) s = Stack() print(len(s)) s.push(2) s.push(5) s.push(9) s.push(12) print(len(s)) ``` * * * * * *