于 2020 年 1 月 7 日更新
len()函数计算对象中的项目数。
其语法如下:
len(obj) -> length
| 参数 | 描述 |
|---|---|
obj |
obj可以是字符串,列表,字典,元组等。 |
这是一个例子:
>>>>>> len([1, 2, 3, 4, 5]) # length of list5>>>>>> print(len({"spande", "club", "diamond", "heart"})) # length of set4>>>>>> print(len(("alpha", "beta", "gamma"))) # length of tuple3>>>>>> print(len({ "mango": 10, "apple": 40, "plum": 16 })) # length of dictionary3
试试看:
# length of listprint(len([1, 2, 3, 4, 5]))# length of setprint(len({"spande", "club", "diamond", "heart"}))# length of tupleprint(len(("alpha", "beta", "gamma")))# length of dictionaryprint(len({ "mango": 10, "apple": 40, "plum": 16 }))
具有讽刺意味的是,len()函数不适用于生成器。 尝试在生成器对象上调用len()将导致TypeError异常。
>>>>>> 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()>>>
试一试:
def gen_func():for i in range(5):yield iprint(len(gen_func()))
len()与用户定义的对象
要在用户定义的对象上使用len(),您将必须实现__len__()方法。
>>>>>> 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>>>
试一试:
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))
