在Python中,`len()`函数用于获取一个对象的长度或元素个数。以下是一些基本用法:
字符串
```python
my_string = "Hello, World!"
length = len(my_string)
print(length) 输出:13
列表
```python
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) 输出:5
元组
```python
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length) 输出:5
字典
```python
my_dict = {"a": 1, "b": 2, "c": 3}
length = len(my_dict)
print(length) 输出:3
自定义类
如果你定义了一个类,并且希望它支持`len()`函数,你需要在类中实现`__len__()`方法:
```python
class MyContainer:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_container = MyContainer([1, 2, 3])
length = len(my_container)
print(length) 输出:3
`len()`函数也可以用于计算可迭代对象(如列表、元组、集合)中元素的个数,以及字典中键值对的个数。对于其他类型的对象,`len()`函数可能会引发`TypeError`异常,除非该对象定义了`__len__()`方法。
需要注意的是,`len()`函数只接受一个参数,并返回一个非负整数,表示容器对象中元素的个数