在 Python 中,可以使用 len()
函数来计算数组(或其他可迭代对象)的长度。
下面是一些示例代码:
- 计算列表的长度:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # 输出:5
- 计算字符串的长度:
my_string = "Hello, world!"
length = len(my_string)
print(length) # 输出:13
- 计算元组的长度:
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length) # 输出:5
- 计算字典的长度(即键值对的数量):
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
length = len(my_dict)
print(length) # 输出:3
无论是列表、字符串、元组还是字典,都可以使用 len()
函数来获取其长度。在处理字符串时,len()
函数返回的是字符串中字符的数量。
评论区