本文共 1568 字,大约阅读时间需要 5 分钟。
len() 用于计算容器中元素的个数。它适用于字符串、列表、元组和字典等数据容器。
str1 = 'abcd'
print(len(str1)) # 输出: 4
list1 = ['孙权', 18, '男']
print(len(list1)) # 输出: 3
tuple1 = (10, 20, 30)
print(len(tuple1)) # 输出: 3
dict1 = {'name': '孙权', 'age': 18, 'sex': '男'}
print(len(dict1)) # 输出: 3
del 用于删除容器中的元素,支持通过索引、切片或键来删除。
str1 = 'abcd'
del str1print(str1) # 输出: 'abcd'(注意:删除操作不会改变字符串内容)
list1 = ['孙权', 18, '男']
del list1[1]print(list1) # 输出: ['孙权', '男']
dict1 = {'name': '孙权', 'age': 18, 'sex': '男'}
del dict1['age']print(dict1) # 输出: {'name': '孙权', 'sex': '男'}
max() 和 min() 用于查询容器中最大或最小值,适用于字符串、列表、元组等数据类型。
asiicastr1 = 'abcdefg'
print(max(str1)) # 输出: 'g'print(min(str1)) # 输出: 'a'
list1 = [10, 20, 30, 40]
print(max(list1)) # 输出: 40print(min(list1)) # 输出: 10
tuple1 = (10, 20, 30, 40)
print(max(tuple1)) # 输出: 40print(min(tuple1)) # 输出: 10
range() 用于生成一系列数据,支持指定起始、结束和步长。
for i in range(1, 10, 1): print(i) # 输出: 1 2 3 4 5 6 7 8 9
for i in range(1, 10, 2): print(i) # 输出: 1 3 5 7 9
for i in range(10): print(i) # 输出: 0 1 2 3 4 5 6 7 8 9
enumerate() 将数据转换为键值对形式,常用于遍历列表、元组等容器。
str1 = 'abcdefg'
for i in enumerate(str1): print(i) # 输出: (0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')
list1 = ['孙权', '男', 18]
for i in enumerate(list1): print(i) # 输出: (0, '孙权'), (1, '男'), (2, 18)
tuple1 = (10, 20, 30, 40)
for i in enumerate(tuple1): print(i) # 输出: (1, 20), (2, 30), (3, 40)
转载地址:http://hkgfk.baihongyu.com/