Python中的len()函数的作用以及使用方法。
发布时间:2023-10-04 16:08:03
在Python中,len()函数用于返回一个对象(字符串,列表,元组等)的长度或项目的数量。
使用方法:
1. 对于字符串,len()函数返回字符串中字符的数量。
string = "Hello World" length = len(string) print(length) # 输出:11
2. 对于列表、元组等可迭代对象,len()函数返回其中项目的数量。
my_list = [1, 2, 3, 4, 5] length = len(my_list) print(length) # 输出:5 my_tuple = (1, 2, 3, 4, 5) length = len(my_tuple) print(length) # 输出:5
3. 对于字典,len()函数返回字典中键值对的数量。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
length = len(my_dict)
print(length) # 输出:3
4. len()函数也可以用于其他类型的对象,如集合、文件等。对于集合,返回集合中项目的数量;对于文件,返回文件中字符或行的数量。
my_set = {1, 2, 3, 4, 5}
length = len(my_set)
print(length) # 输出:5
file = open('data.txt', 'r')
length = len(file.readlines())
print(length) # 输出:行数
file.close()
需要注意的是,len()函数只能用于可迭代对象或具有确定长度的对象。对于自定义的对象,可通过在其类中实现\_\_len\_\_()方法来定义长度。
