本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
len(object)
-
object:想要获取长度的对象。可以是序列(如字符串、字节、元组、列表或范围)或集合(如字典、集合或冻结集)。
返回值:
下面是一些使用 len() 函数的示例:
-
示例:
# 字符串的长度
string = "Hello, World!"
print(len(string))
# 输出:13
# 列表的长度
list_example = [1, 2, 3, 4, 5]
print(len(list_example))
# 输出:5
# 元组的长度
tuple_example = (1, 2, 3)
print(len(tuple_example))
# 输出:3
# 字典的长度(键-值对的数量)
dict_example = {'a': 1, 'b': 2, 'c': 3}
print(len(dict_example))
# 输出:3
# 集合的长度
set_example = {1, 2, 3, 4, 5}
print(len(set_example))
# 输出:5
-
对于自定义对象,如果需要支持 len() 函数,可以在类中实现一个特殊的 __len__() 方法:
在下面的示例中,MyClass 类实现了 __len__() 方法,使其对象可以使用 len() 函数来获取长度:
class MyClass:
def __init__(self, value):
self.value = value
# 实现 __len__() 方法
def __len__(self):
return len(self.value)
obj = MyClass([1, 2, 3, 4, 5])
print(len(obj))
# 输出:5


本篇文章来源于微信公众号: 码农设计师