发布时间:2025-12-10 23:48:44 浏览次数:12
len函数用于获取一个对象的长度或元素个数。它的使用方法如下:
对于字符串,可以使用len函数获取字符串的长度。string = "Hello World"length = len(string)print(length) # 输出:11对于列表、元组、集合等可迭代对象,可以使用len函数获取其中元素的个数。list1 = [1, 2, 3, 4, 5]length = len(list1)print(length) # 输出:5tuple1 = (1, 2, 3, 4, 5)length = len(tuple1)print(length) # 输出:5set1 = {1, 2, 3, 4, 5}length = len(set1)print(length) # 输出:5对于字典,可以使用len函数获取其中键值对的个数。dict1 = {"name": "John", "age": 25, "city": "New York"}length = len(dict1)print(length) # 输出:3对于其他对象,len函数可能会返回其他含义的值或引发TypeError异常,具体取决于对象的实现。number = 12345length = len(number)print(length) # TypeError: object of type 'int' has no len()总之,len函数可以用于获取字符串、列表、元组、集合、字典等对象的长度或元素个数。