python小技巧
01将字符串倒转
my_string = "啊,生存还是毁灭 "
reversed_string = my_string[::-1 ]
02将英文单词的首字母大写通过title()方法来实现首字母的大写
my_string = " my name is wei xiang " # 通过title()来实现首字母大写 new_string = my_string.title()
print (new_string) # My Name Wei Xiang
03给字符串去重
my_string = "dddbbeacf " # 通过set()来进行去重 temp_set = set(my_string) # 通过join()来进行连接 new_string = '' .join(temp_set)
print (new_string) # dfbcae
04拆分字符串
string_1 = " My name is kaixin mahua " string_2 = "开心 , 麻 1, 花 2 " # 默认的分隔符是空格,来进行拆分 print (string_1.split()) # ['My', 'name', 'is', 'kaixin', 'mahua'] print (string_2.split( ' , ' )) # ['开心', '麻 1', '花 2']
05将字典中的字符串连词成串
list_of_strings = [ ' My ' , ' name ' , ' is ' , 'DongMei ' , 'DaQiao ' ] # 通过空格和join来连词成句 print ( ' ' .join(list_of_strings)) # My name is DongMei DaQiao
06查看列表中各元素出现的个数
from collections import Counter
my_list = [ 'a ' , 'a ' , ' b ' , ' b ' , ' b ' , ' c ' , ' d ' , ' d ' , ' d ' , ' d ' , ' d ' ]
count = Counter(my_list) print (count) # Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1}) print (count[ ' b ' ]) # 单独的“b”元素出现的次数# 3 print (count.most_common(1)) # 出现频率最多的元素# [('d', 5)]
07 合并两字典
dict_1 = { ' apple ' : 0, ' banana ' : 3 }
dict_2 = { ' grape ' : 1, ' orange ' : 9 } # 方法一 combined_dict = {**dict_1, ** dict_2}
# 方法二 dict_1.update(dict_2)
# 方法三 print (dict(dict_1.items() | dict_2.items())) # {'apple': 0, 'banana': 3, 'grape': 1, 'orange': 9}
08查看程序运行的时间
import time
start_time = time.time()
end_time = time.time()
time_taken_in_micro = (end_time - start_time) * (10 ** 6 ) print (time_taken_in_micro)
09 列表的扁平化 有时候会存在列表当中还嵌套着列表的情况
from iteration_utilities import deepflatten
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10 ]]]]
print(list(deepflatten(l, depth=3))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10查看列表当中是否存在重复值
def unique(l):
if len(l)== len(set(l)):
print ( " 不存在重复值 " )
else :
print ( " 存在重复值 " )
unique([t ,l,p]) # 不存在重复值 unique([l,t,t]) # 存在重复值
11 数组的转置
array = [[ 'l ' , '3 ' ], [ 't ' , '2 ' ], [ 't ' , '1 ' ]]
transposed = zip (* array) print (list(transposed)) # [('l', 't', 't'), ('3', '2', '1')]
12找出两列表当中的不同元素
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison) # 返回第一个列表的不同的元素 difference([1,2,6], [1,2,5]) # [6]
13将两列表变成键值对将两个列表合并成一个键值对的字典
def to_dictionary(keys, values):
return dict( zip (keys, values))
keys = [ " 三 " , " 二 " , " 意 " ]
values = [3, 2, 1 ] print (to_dictionary(keys, values)) # {'三': 3, '二': 2, '意': 1}
14对字典进行排序根据字典当中的值 对字典进行排序
d = { ' apple ' : 9, ' grape ' : 4, ' banana ' : 6, ' orange ' : 8 } # 方法一 sorted(d.items(), key = lambda x: x[1]) # 从小到大排序# [('grape', 4), ('banana', 6), ('orange', 8), ('apple', 9)] sorted(d.items(), key = lambda x: x[1], reverse = True) # 从大到小排序# [('apple', 9), ('orange', 8), ('banana', 6), ('grape', 4)] # 方法二 from operator import itemgetter print (sorted(d.items(), key = itemgetter(1))) # [('grape', 4), ('banana', 6), ('orange', 8), ('apple', 9)]
15列表中最大/最小值的索引
1 list1 = [1,2,3,2,1 ] 2 print (list1.index(max(list1))) # 2 3 print (list1.index(min(list1))) # 0
16. +=与= +的不同
# 案例1 a = [1,2 ]
b = a
a = a + [3, 4] # 会生成一个新列表 print (a) # [1,2,3,4] print (b) # [1,2] # 案例2 a = [1,2 ]
b = a
a += [3, 4] # 相当于extend,列表a后直接添加元素 print (a) # [1,2,3,4] print (b) # [1,2,3,4]
17.给多个变量赋值
list = [3, 1, 9 ]
a, b, c = list # a=3,b=1,c=9 def f(): return 6 0 1 q, w, e = f() # q=6,w=0,e=1
18. 获取变量内存占用
import sys
value = " helo moto " sys. getsizeof (value)
19.字典集合推导式
values = {i : i*i for i in range(3)} # {0:0, 1:1, 2:4}
20.emoji表情
import emoji
emoji.emojize( ' Python is :thumbs_up: ' ) # 返回的一个大拇指表情
21.map+lambda 惊喜组合
x = [1, 2, 3 ]
y = map ( lambda x : x ** 2 , x) # 映射 print (list(y)) # [1, 4, 9]
22.sh调用系统命令,写shell脚本
import sh
sh.echo( " 情系中国结,联通四海心 " ) # 返回“情系中国结,联通四海心” sh.which( " python " ) # 返回python所在路径
23.优雅赋值,拆包
a, *mid, b = [1, 2, 3, 4, 5, 6 ] print (a, mid, b) # 1 [2, 3, 4, 5]
24.使用下划线忽略变量
L = [1,3,5,7 ]
a, _, b, _ = L print (a,b) # 1 5
25.放置占位符
def fun(): pass #定义一个函数但尚未弄清楚如何实现它时,可以放置。 或者: def fun():
...
26.浅拷贝
a = [1,3 ]
b = a.copy() # 这里还可以用 b = a[:] b[0]=3 print (a,b) # [1,3] [3,3]
27.采用多种方式将字符串格式化
lang = ' python ' print (f ' {lang} is most popular language in the world ' ) print ( ' I like {} ' .format(lang)) print ( ' I like %s ' %(lang)) # I like python
28.简单装饰器
def sheng(input): return lambda : " 省前 " + input() + " 省后 " def shi(input): return lambda : " 市前 " + input() + " 市后 " @sheng
@shi def run(): return " 泗阳县 " print (run()) # 省前 市前 泗阳县 市后 省后
29.startswith,endswith
print ( " http://foofish.net " .startswith(( ' http ' , ' https ' ))) # True print ( " http://foofish.net " .endswith(( ' net ' , ' https ' ))) # True
家是爱的港湾,责备、焦虑、攀比、翻旧账…无论对于家中零星的个体还是小家这个整体,都毫无意义,最后留下的也大都是沉默。格局小的人,在家里会为了鸡零狗碎的小事斤斤计较,格局大的人,懂得小事不争,错事不怨,把家经营得和睦温馨。中国家庭的悲剧,多数都源自于遇事爱责备的相处模式,家庭里有欢声笑语,也有剪不断理还乱的纠纷,没有谁能置身事外。能包容,就少去责备,能接纳,就别强求改变。家乃是社会之缩影。我们怎么经营一个家,就怎么经营一生。