标签:方法 rom key love sort 深拷贝 ima lis 基础知识
1 # format 2 s0 = "我叫{},今年{}岁了,我喜欢{}".format("王力宏",46,"娃哈哈") #按位置格式化 3 s1 = "我叫{0},今年{2}岁了,我喜欢{1}".format("王力宏","娃哈哈",46) #指定位置格式化 4 s2 = "我叫{name},今年{age}岁了,我喜欢{lover}".format(name = "王力宏",age = 46,lover = "徐静蕾") #指定关键字 5 print(s0) 6 print(s1) 7 print(s2)
1 li = ["a","b","c"] 2 li.extend("xyz") 3 print(li)
1 l1 = [‘c‘, ‘d‘, ‘r‘, ‘d‘, ‘r‘ ,‘a‘, ‘C‘] 2 l2 = list(set(l1)) 3 l2.sort(key=l1.index) #set内元素是无序的,用sort可以按照L1的元素顺序排序 4 print(l2)
1 l1 = [‘c‘, ‘d‘, ‘r‘, ‘d‘, ‘r‘ ,‘a‘, ‘C‘] 2 l2 = [] 3 for el in l1: 4 if el not in l2: 5 l2.append(el) 6 print(l2)
1 l1 = [‘c‘, ‘d‘, ‘r‘, ‘d‘, ‘r‘ ,‘a‘, ‘C‘] 2 l1.sort() 3 l2=[] 4 n = 0 5 while n < len(l1): 6 if l1[n] not in l2: 7 l2.append(l1[n]) 8 n = n + 1 9 else: 10 n = n + 1 11 print(l2)
1)浅拷贝: 只拷贝第一层,下层沿用(地址相同)
1 l1 = ["蚂蚁","蓝猫","影魔"] 2 l2 = l1.copy() 3 l1.append("帕克") 4 print(l1) 5 print(l2) 6 print(id(l1),id(l2)) 7 # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘, ‘帕克‘] 8 # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘] 9 # 2527144744328 2527144744264
l1 = ["蚂蚁","蓝猫","影魔",["巨魔","飞机","莉娜"]] l2 = l1.copy() l1[3].append("帕克") print(l1) print(l2) print(id(l1[3]),id(l2[3])) # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘, [‘巨魔‘, ‘飞机‘, ‘莉娜‘, ‘帕克‘]] # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘, [‘巨魔‘, ‘飞机‘, ‘莉娜‘, ‘帕克‘]] # 2988850058632 2988850058632
2)深拷贝: 完全不同的个体
import copy l1 = ["蚂蚁","蓝猫","影魔",["巨魔","飞机","莉娜"]] l2 = copy.deepcopy(l1) #注意用法,需要导入copy模块 l1[3].append("帕克") print(l1) print(l2) print(id(l1[3]),id(l2[3])) # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘, [‘巨魔‘, ‘飞机‘, ‘莉娜‘, ‘帕克‘]] # [‘蚂蚁‘, ‘蓝猫‘, ‘影魔‘, [‘巨魔‘, ‘飞机‘, ‘莉娜‘]] # 1751479821960 1751479823368
1 dic = dict.fromkeys(["jay","JJ"],["周杰伦","林俊杰"]) 2 print(dic) 3 # {‘jay‘: [‘周杰伦‘, ‘林俊杰‘], ‘JJ‘: [‘周杰伦‘, ‘林俊杰‘]} 4 dic.get("jay").append("哈哈哈") 5 print(dic) 6 # {‘jay‘: [‘周杰伦‘, ‘林俊杰‘, ‘哈哈哈‘], ‘JJ‘: [‘周杰伦‘, ‘林俊杰‘, ‘哈哈哈‘]} 由于dic中jay和JJ共用一个列表,jay添加元素,相应JJ也添加元素
r+模式是追加读写,但并不是只能先读后写,也可以先写后读,注意先读后写时,只能再末尾添加
(,) 注意中间要有逗号
split()可以分割字符串成列表,而join()可以将列表中的元素拼接成字符串
标签:方法 rom key love sort 深拷贝 ima lis 基础知识
原文地址:https://www.cnblogs.com/listash/p/9321880.html