在Python中,`len()`函数用于获取序列(如字符串、列表、元组、集合)或映射(如字典)的长度。以下是`len()`函数的基本用法:
1. 获取字符串长度:
string = "Hello, World!"
length = len(string)
print("字符串的长度是:", length) 输出:字符串的长度是: 13
2. 获取列表长度:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("列表的长度是:", length) 输出:列表的长度是: 5
3. 获取元组长度:
tuple_1 = (1, 2, 3, 4, 5)
length = len(tuple_1)
print("元组的长度是:", length) 输出:元组的长度是: 5
4. 获取集合长度:
set_1 = {1, 2, 3, 4, 5}
length = len(set_1)
print("集合的长度是:", length) 输出:集合的长度是: 5
5. 获取字典长度:
dict_1 = {'name': 'Alice', 'age': 20, 'gender': 'female'}
length = len(dict_1)
print("字典的长度是:", length) 输出:字典的长度是: 3
empty_list = []
if len(empty_list) == 0:
print("列表为空")
else:
print("列表不为空") 输出:列表为空
使用`len()`函数非常简单,只需将需要计算长度的对象作为参数传递给`len()`函数即可。