Skip to content

Files

Latest commit

8b65768 · Jun 26, 2020

History

History
155 lines (116 loc) · 2.32 KB

50.md

File metadata and controls

155 lines (116 loc) · 2.32 KB

Python len()函数

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


于 2020 年 1 月 7 日更新


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

其语法如下:

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

这是一个例子:

>>> 
>>> 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

试试看:

# 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异常。

>>>
>>> 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 i

print(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))