列表内置方法
只给列表用
lt = [1,2,3]
1.索引取值/索引修改值
print(lt[2]) #3取
lt[0] = 2
print(lt) #[2,2,3]改
2.索引切片
print(lt[0:1])
3.成员运算in/not in
print(2 in lt) #T
print(2 not in lt) #F
4.for循环
for i in lt:
print(i)
5.长度len
print(len(lt)) #3
6.append():追加值
lt.append(4) #[2,2,3,4]
7.sort():排序
lt = [2,3,1]
lt.sort()
print(lt) #[1,2,3]
(lt.sort(key=lambda i:i[1])
print(lt)#首字母排序)
8.reverse():反转
lt = [1,2,3]
lt.reverse()
print(lt)#[3,2,1]
9.index():获取元素索引
print(lt.index(2)) #1
10.clear():清空列表
lt.clear()
print(lt)
11.copy():复制列表
lt1 = lt.copy()
print(lt1)
12.extend():扩展列表
lt1 = [1,2,3]
lt2 = [3,4,5]
lt1.extend(lt2)
print(lt1) #[1,2,3,3,4,5]
13.remove():移除
lt.remove(3)
print(lt) #[1,2]
14.insert():按照索引往前插入值
lt.insert(0,0.5)
print(lt) #[0.5,1,2,3]
字典的内置方法
只能字典使用
xuan_info_dic = {'name':'1a','height':152,'weight':111,'hobby':['2b','3c','4d']}
1.按key取值/按key修改值/按key增加值
print(xuan_info_dic['height']) #取值
xuan_info_dic['height']=xuan_info_dic['height']+1
print(xuan_info_dic['height']) #修改值
xuan_info_dic['age']=30
print(xuan_info_dic) #增加值
2.成员运算(比较的是key)
print('age' in xuan_info_dic) #T
3.for循环(对key循环)
for i in xuan_info_dic:
print(i)
4.key()/values()/items()
print(xuan_info_dic.key()) #所有的key ##dict_keys(['name','height','weight','hobby'])
print(xuan_info_dic.values()) #所有的值
##dict_values(['1a',152,111,['2b','3c','4d']])
print(xuan_info_dic.items()) #所有的键值对(以列表存储)
##dict_items([('name':'1a'),('height':152),('weight':111),('hobby':['2b','3c','4d'])])
for i in xuan_info_dic.items():
print(i[0] + '***' + str(i[1])) #键值对以***相连
name***1a
height***152
……
5.get():取值
print(xuan_info_dic.get('height',150))#找到了就找到了;没有值就返回None,如果给定了(150)就算给定的值(150)
购物车没有的话为1,有的话加1
shopping_car = {}
if shopping_car.get('ww'): #如果有的话加1
shopping_car['ww'] = shopping_car['ww']+1
else: #否则直接为1
shopping_car['ww']=1
print(shopping_car)
6.update():扩展字典
dic1 = {'a':1}
dic2 = {'b':2}
dic1.update(dic2)
print(dic1)#{'a':1,'b':2}
7.setddefault():有则不更改,没有则增加
dic1 = {'a':1}
dic1.setdefault('a',2)
print(dic1) #{'a':1}(因为有a所以不改)