使用Python的len()函数找到列表、字符串和字典的长度
发布时间:2023-07-01 22:18:50
在Python中,我们可以使用 len() 函数来获取列表、字符串和字典的长度。
1. 获取列表的长度:
my_list = [1, 2, 3, 4, 5] length = len(my_list) print(length) # 输出:5
2. 获取字符串的长度:
my_string = "Hello, World!" length = len(my_string) print(length) # 输出:13
3. 获取字典的长度时,我们需要注意的是,len() 函数将返回字典中键值对的数量:
my_dict = {"name": "John", "age": 25, "city": "New York"}
length = len(my_dict)
print(length) # 输出:3
需要注意的是,对于字符串,len() 函数返回的是字符串的字符数,而不是单词的数量。如果你想要计算字符串中单词的数量,可以使用 len() 函数结合 split() 方法:
my_string = "Hello, World!" words = my_string.split() word_count = len(words) print(word_count) # 输出:2
需要注意的是,使用 len() 函数时,列表、字符串和字典都被视为一个整体,即使它们包含了更复杂的结构。例如,在列表中嵌套了其他列表,len() 函数只会返回最外层列表的长度。
希望这些示例能帮助你理解如何使用 len() 函数来查找列表、字符串和字典的长度。
