python

python中len()函数怎么使用

小亿
103
2023-11-06 09:53:28
栏目: 编程语言

len()函数用于返回一个对象的长度或者元素的数量。它的使用方式如下:

  1. 对于字符串:
string = "Hello World"
length = len(string)
print(length)  # 输出:11
  1. 对于列表、元组和集合等容器类型:
my_list = [1, 2, 3, 4]
length = len(my_list)
print(length)  # 输出:4

my_tuple = ('a', 'b', 'c')
length = len(my_tuple)
print(length)  # 输出:3

my_set = {1, 2, 3, 4}
length = len(my_set)
print(length)  # 输出:4
  1. 对于字典:
my_dict = {'a': 1, 'b': 2, 'c': 3}
length = len(my_dict)
print(length)  # 输出:3
  1. 对于其他对象,len()函数的使用取决于具体的对象类型。例如,在自定义类中,可以通过定义__len__()方法来控制len()函数的行为。

0
看了该问题的人还看了