2021-01-20 Python编程特殊小技巧汇集
Python編程特殊小技巧匯集
Python作為一種高級編輯語言,有很多使用的小技巧,分享一期。
1、變量值互換
a = 0b = 1a,b?=?b,?a2、連續賦值
a, b = 2, 13、自動解包賦值
a,b,c,d = [1,3,4,'domi']aa,*others = [1,3,4,'domi']>>> others[3, 4, 'domi']4、鏈式比較
a = 10if 5<= a <= 15:????print('Hello?world')?????#?等價于?if?5<=?a?and?a?<=?15: print('Hello world')5、重復列表
a?=?[1,'domi']*2>>> a[1, 'domi', 1, 'domi']6、重復字符串???????
>>> a[1]*2'domidomi'7、三目運算
a = 10b?=?True?if?a==10 else False>>> bTrue等價于if?a==10: b = Trueelse:????b = False8、字典合并
a?=?{"a":1}b?=?{"b":2}>>>?{**a,?**b}{'a': 1, 'b': 2}9、字符串反轉???????
s = "domi"s1 = s[::-1]10、列表轉為字符串???????
s = ['d','o','m','i']s1?= "".join(s)>>> s1'domi'11、字典推導式
a?=?{x:x**2?for?x?in?range(3)}>>> a{0: 0, 1: 1, 2: 4}12、字典key和value互換???????
a_dict = {'a': 1, 'b': 2, 'c': 3}{value:key for key, value in a_dict.items()}{1: 'a', 2: 'b', 3: 'c'}13、用counter查找列表中出現最多的元素
a = [1,2,3,3,0]from?collections?import?Counterb?=?Counter(a)b.most_common(1)[(3,?2)]??#?3出現的次數最多,為2次14、賦值表達式,:=,可以將變量賦值和表達式放在一行
import res?="helloworld"match?=?re.search('o', s)if?match:????num?=?match.group(0)else:????num = Nonenum3和4可以合并為一行代碼
if?match?:=?re.search('o',?s): num = match.group(0)else: num = None15、isintance函數用來判斷實例的類型???????
a?=?1.2isinstance(a,?(int, float)) b = "str"isinstance(a,?int)16、判斷字符串是否某個字符開始或者結束,startswith,endswith???????
s?=?"123asdz"s.startswith("1") s.endswith(("z","a"))17、http.server共享文件
python3?-m?http.server效果如下,方便在瀏覽器共享文件目錄,方便在局域網共享文件
?
18、查找列表中出現次數最多的數字???????
a = [1,2,3,3,0]max(set(a),?key=a.count)19、擴展列表???????
a.extend(['domi','+1'])>>> a[1, 2, 3, 3, 0, 'domi', '+1']20、列表負數索引???????
a[-2]'domi'21、列表切片,???????
a = [1,2,3,'domi','mi']>>>?a[2:4]??#?提取第3個位置到第5個位置(不包含第5個位置)的數據[3, 'domi']>>>?a[:3]?#?提取前3個數據[1, 2, 3]>>> a[::2] # 提取偶數項[1, 3, 'mi']>>>?a[1::2]?#?提取奇數項[2, 'domi']>>>?a[::-1]?#?列表反轉['mi', 'domi', 3, 2, 1]22、二維數組轉為一維數組???????
import?itertoolsa = [[1,2],[3,4],[5,6]]b?=?itertools.chain(*a)>>> list(b)[1, 2, 3, 4, 5, 6]23、帶索引的迭代???????
a?=?['d','o','m','i']for?index,?value?in?enumerate(a):????print('第%d個數據為%s'?%(index, value))????第0個數據為d第1個數據為o第2個數據為m第3個數據為i?24、列表推導式???????
a?=?[x*3 for x in range(3)]>>> a[0, 3, 6]a = [x*3 for x in range(10) if x%2 == 0]>>> a[0, 6, 12, 18, 24]25、生成器表達式???????
ge = (x*2 for x in range(10))>>> ge<generator object <genexpr> at 0x000001372D39F270>>>> next(ge)0>>>>>> next(ge)2>>> next(ge)4>>> next(ge)6>>> next(ge)8>>> next(ge)10>>> next(ge)12>>> next(ge)14>>> next(ge)16>>> next(ge)18>>> next(ge) # 迭代結束Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration26、集合推導式???????
>>> nums = {n**2 for n in range(10)}>>> nums{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}27、判斷key是否存在字典中判斷key是否存在字典中???????
>>> d = {"1":"a"}>>> d['2']Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: '2'>>> d['1']'a'>>> '1' in dTrue>>> '2' in dFalse>>> d.get('1')'a'>>> d.get('2')28、打開文件???????
with open('foo.txt', 'w') as f:????f.write("hello world")29、兩個列表組合成字典
a = ["One","Two","Three"]b = [1,2,3]dictionary = dict(zip(a, b))print(dictionary)30、去除列表中重復元素
???????
my_list = [1,4,1,8,2,8,4,5]my_list = list(set(my_list))31、打印日歷
import calendar
>>> print(calendar.month(2021, 1)) January 2021Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 3132、匿名函數???????
def add(a, b): return a+b# 等同于add = lambda a,b:a+badd(1,2)總結
以上是生活随笔為你收集整理的2021-01-20 Python编程特殊小技巧汇集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-01-13 Matlab求解微
- 下一篇: 2021-01-20 Matlab画图技