python大杂铺
程序员文章站
2022-06-19 18:26:31
Map函数 1 def format_name(s): 2 3 return s[0].upper() + s[1:].lower() 4 5 6 7 print map(format_name, ['adam', 'LISA', 'barT']) View Code 去掉string(英文状态)的 ......
-
map函数
1 def format_name(s): 2 3 return s[0].upper() + s[1:].lower() 4 5 6 7 print map(format_name, ['adam', 'lisa', 'bart'])
-
去掉string(英文状态)的标点符号
1 import string 2 3 4 def removepunctuation(text): 5 '''去掉字符串中标点符号 6 ''' 7 # 方法一:使用列表添加每个字符,最后将列表拼接成字符串,目测要五行代码以上 8 temp = [] 9 for c in text: 10 if c not in string.punctuation: 11 temp.append(c) 12 newtext = ''.join(temp) 13 print(newtext) 14 15 # 方法二:给join传递入参时计算符合条件的字符 16 b = ''.join(c for c in text if c not in string.punctuation) 17 print(b) 18 return newtext
-
continue,break的区别
-
""" while true: print(1) break # 跳出当前循环 print(11) print(2) """ """ print(0) while true: print(1) continue # 结束本次循环,进行下次循环 print(11) print(2) """ 示例: 使用break实现: 1-100 start = 1 while true: print(start) start = start + 1 if start == 100: print(start) break 输出:1 2 3 4 5 6 7 8 9 10 """ start = 1 while start < 11: if start == 7: pass else: print(start) start = start + 1 """ """ start = 1 while start < 11: if start == 7: start = start + 1 continue else: print(start) start = start + 1 """
-
字典
-
dic = { 'k1': 'v1', 2: 'v1', false: 'v1', (11,22,33): 'v1', }
1. 可变不可变
不可变:str,int,bool,tuple
可变: list,dict,set
2. 字典查找速度快,基于哈希索引
问题1. 字典的key都能是什么?
布尔值: true= 1; false=0 -
深浅copy:
1.copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
dic1 = { 'k1': 'v1', 'k2': [11,22,33,44] } dic2 = dic1.copy() print(dic1,dic2) dic1['k2'].append(666) print(dic1,dic2)
输出:
2. copy.deepcopy() 深拷贝,拷贝对象及其子孙对象
1 dic1 = { 2 'k1': 'v1', 3 'k2': [11,22,33,44] 4 } 5 import copy 6 dic2 = copy.deepcopy(dic1) 7 print(dic1,dic2) 8 dic1['k2'].append(666) 9 print(dic1,dic2)
深copy时,dic1有两层对象,可以理解为父对象和子孙对象;一层是'k1'(key1): 'v1'(value1),'k2'(key2):[11,22,33,44] (value2),而value2又是一层对象(子对象)
输出:
深浅copy:
下一篇: 用init玩转 Linux 运行级别