公共方法、len、del、max、min、range、enumerate
作者:互联网
1. len()
# 1. 字符串 str1 = 'abvdse' print(len(str1)) # 6 # 2. 列表 list1 = [10, 20, 30, 40] print(len(list1)) # 4 # 3. 元组 t1 = (10, 50, 60, 20, 80) print(len(t1)) # 5 # 4. 集合 s1 = {20, 50, 40} print(len(s1)) # 3 # 5. 字典 dict1 = {'name': 'ashd', 'age': 20} print(len(dict1)) # 2
2. del 或 del()
str1 = 'abvdse' list1 = [10, 20, 30, 40] t1 = (10, 50, 60, 20, 80) s1 = {20, 50, 40} dict1 = {'name': 'ashd', 'age': 20} del str1 # 结果:name 'str1' is not defined(找不到str1) # print(str1) del (list1[1]) # 结果:[10, 30, 40] # print(list1) del (t1) # 结果:name 'str1' is not defined # print(t1) del (dict1['name']) # 结果:{'age': 20} print(dict1)
3. max()和 min()
str1 = 'abvdse' list1 = [10, 20, 30, 40] dict1 = {'name': 'ashd', 'age': 20} # max最大值 print(max(str1)) # v print(max(list1)) # 40 print(max(dict1)) # name # min最小值 print(min(str1)) # a print(min(list1)) # 10 print(min(dict1)) # age
4. range(start开始,end结束,step步长)
# 结果:range(1, 6) # print(range(1, 6, 1)) # for i in range(1, 6, 1): # 结果:1 2 3 4 5 # print(i) # for i in range(1, 6): # 结果:1 2 3 4 5 # print(i) # for i in range(1, 10, 2): # 结果:1 3 5 7 9 # print(i) for i in range(10): # 结果:0 1 2 3 4 5 6 7 8 9 print(i)
注意:1.如果不写开始,默认从0开始
2.如果不写步长,默认为1
5. enumerate()
语法:enumerate(可遍历对象,start=0)
注意:start参数用来设置遍历数据的下标的起始值,默认为0
list1 = ['a', 'b', 'c', 'd', 'e'] # enumerate 返回结果是元组,元组第一个数据是原迭代对象的数据对应的下标,元组第二个数据是原迭代对象的数据 for i in enumerate(list1): print(i)
list1 = ['a', 'b', 'c', 'd', 'e'] for i in enumerate(list1, start=1): print(i)
list1 = ['a', 'b', 'c', 'd', 'e'] for index, char in enumerate(list1, start=1): print(f'下标是{index}, 对应的字符是{char}')
标签:10,20,min,max,str1,list1,enumerate,print,dict1 来源: https://www.cnblogs.com/yz-b/p/16641395.html