魔法函数len的用法举例
时间: 2023-06-20 18:10:03 浏览: 67
魔法函数 `len()` 用于返回对象的长度或元素个数。下面是一些常见的使用示例:
1. 获取字符串长度
```python
string = "Hello World"
print(len(string)) # 输出 11
```
2. 获取列表、元组或集合中元素的个数
```python
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3)
my_set = {1, 2, 3, 4}
print(len(my_list)) # 输出 5
print(len(my_tuple)) # 输出 3
print(len(my_set)) # 输出 4
```
3. 获取字典中键值对的个数
```python
my_dict = {"a": 1, "b": 2, "c": 3}
print(len(my_dict)) # 输出 3
```
4. 获取文件中行数
```python
with open("file.txt", "r") as f:
print(len(f.readlines())) # 输出文件中的行数
```
5. 获取自定义类的长度
可以在自定义类中实现 `__len__()` 方法,以便在使用 `len()` 函数时返回自定义类的长度。
```python
class MyClass:
def __init__(self, my_list):
self.my_list = my_list
def __len__(self):
return len(self.my_list)
my_class = MyClass([1, 2, 3, 4, 5])
print(len(my_class)) # 输出 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)