1.列表
1 string = ‘list‘ 2 3 #字符串 -》 列表 4 list1 = list(string) # [‘l‘, ‘i‘, ‘s‘, ‘t‘] 5 6 #列表 - 》字符串 7 string1 = ‘‘.join(list1) # list 8 9 #增加 10 list1 = list(‘I have a pen‘) 11 list1.append(‘!‘)#末尾增加一个元素[‘I‘, ‘ ‘, ‘h‘, ‘a‘, ‘v‘, ‘e‘, ‘ ‘, ‘a‘, ‘ ‘, ‘p‘, ‘e‘, ‘n‘, ‘!‘] 12 list1.insert(2,‘this is a chuanqi ‘) 13 #[‘I‘, ‘ ‘, ‘chuanqi‘, ‘h‘, ‘a‘, ‘v‘, ‘e‘, ‘ ‘, ‘a‘, ‘ ‘, ‘p‘, ‘e‘, ‘n‘, ‘!‘] 14 15 #删除 16 list1.pop(-1) #删除指定索引的元素,不填的话默认删除的元素,并return被删除的元素 17 del list1[-1] 18 list1.remove(‘n‘) 19 #删除指定的元素,如果不存在,则会报错,没有返回值 20 21 #修改 22 list_new = [1,2,3,4,5] 23 list_new[0] = 8 # 元素赋值 24 list_new[0:2] = list(‘05‘) #分片赋值, [‘0‘, ‘5‘, 3, 4, 5] 25 list_new[1:1] = list(‘1234‘)#分片赋值,插入元素 26 #[1, ‘1‘, ‘2‘, ‘3‘, ‘4‘, 2, 3, 4, 5] 27 list_new[1:3] = list[] #分片赋值 ,删除元素 28 #[1, 4, 5] 29 30 #查找 31 list_new = [1,2,3,4,5] 32 if 1 in list_new: 33 index = list_new.index(1) 34 print(index) # 查找元素下标 35 #0 36 37 #拼接 38 list_new = [1,2,3,4,5] 39 list_n = [8,9,10] 40 list_new.extend(list_n) 41 print(list_new)# 向列表中添加元素 42 #[1, 2, 3, 4, 5, 8, 9, 10] 43 44 #逆置 45 list_new = [1,2,3,4,5] 46 list_new.reverse() 47 print(list_new) #list_new = [1,2,3,4,5] 48 49 #去重 50 51 #1 52 l1 = [‘b‘,‘c‘,‘d‘,‘c‘,‘a‘,‘a‘] 53 l2 = list(set(l1)) 54 #2 55 l2.sort(key=l1.index) #保持原来的顺序 56 #3 57 l1 = [‘b‘,‘c‘,‘d‘,‘c‘,‘a‘,‘a‘] 58 l2 = [] 59 for i in l1: #[l2.append(i) for i in l1 if not i in l2] 60 if not i in l2: 61 l2.append(i) 62 print l2 #保持原来的顺序
2.元组
1 #操作和列表相似,但元组不能修改 2 tuple1 = tuple([1,2,3,4]) 3 #将列表转换为元组
3.字典
1 #创建 2 dict1 = { 3 ‘key‘:‘value‘, 4 ‘key1‘:‘value1‘ 5 } 6 a = [(‘key1‘,‘value1‘),(‘key2‘,‘value2‘)] 7 dict1 = dict(a) 8 dict1 = {}.fromkeys([‘key1‘,‘key2‘],‘default_value‘) #从键值创建dict 9 dict1 = dict(key1=‘value1‘,key2=‘value2‘) 10 11 #增加 12 dict1[‘key3‘]=‘value3‘ #字典可以自动添加 13 dict1.setdefault(‘key5‘,‘N/A‘) #如果不存在,就设置默认值 14 dic = {‘name‘:‘egon‘,‘age‘:18,‘salary‘:50000,‘hobbies‘:‘happy‘,‘height‘:180} 15 dic.setdefault(‘height‘,185) 16 print(dic) 17 #{‘name‘: ‘egon‘, ‘age‘: 18, ‘salary‘: 50000, ‘hobbies‘: ‘happy‘, ‘height‘: 180} 18 19 #删除 20 del dict1[‘key3‘] 21 print dict1.pop(‘key2‘) #popitem随机删除 和列表的pop一样 22 #dict1.clear() #深删除,即使有拷贝 也会被删除 23 24 #修改 25 if ‘key1‘ in dict1: 26 dict1[‘key1‘]=‘new_value_1‘ 27 28 #查找 29 if ‘key1‘ in dict1: 30 print dict1[‘key1‘] 31 if dict1.has_key(‘key1‘): 32 print dict1[‘key1‘] 33 print dict1.get(‘key3‘,‘not exists‘) #宽松访问 34 print dict1.keys(),dict1.values() 35 36 #拼接 37 dict2 = dict(key4 = ‘value4‘) #从字典更新另一个字典 38 dict1.update(dict2) 39
时间: 2024-10-13 09:28:09