要读取 Python 中序列(例如列表、元组、字符串等)的元素个数,可以使用内置函数 len()
。这个函数接受一个序列作为参数,并返回该序列中元素的数量。
示例:
# 读取列表的元素个数
my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)
print("List length:", list_length)
# 读取元组的元素个数
my_tuple = (1, 2, 3, 4, 5)
tuple_length = len(my_tuple)
print("Tuple length:", tuple_length)
# 读取字符串的字符个数
my_string = "Hello, World!"
string_length = len(my_string)
print("String length:", string_length)
输出:
List length: 5
Tuple length: 5
String length: 13
len()
函数用于确定每个序列中的元素数量。