温馨提示×

python如何查看元素个数

小亿
81
2024-09-13 14:38:59
栏目: 编程语言

在Python中,可以使用内置函数len()来查看元素的个数。例如,对于列表、元组和字符串等可迭代对象,可以直接使用len()函数获取其长度。

# 示例1:获取列表长度
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("列表元素个数:", length)

# 示例2:获取元组长度
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print("元组元素个数:", length)

# 示例3:获取字符串长度
my_string = "hello world"
length = len(my_string)
print("字符串元素个数:", length)

输出结果:

列表元素个数: 5
元组元素个数: 5
字符串元素个数: 11

注意:len()函数不能直接获取字典的元素个数,因为字典是键值对的集合。如果需要获取字典的元素个数,可以使用len(dictionary)或者len(dictionary.keys())

0