溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python編程技巧有哪些

發(fā)布時間:2022-10-21 14:33:01 來源:億速云 閱讀:116 作者:iii 欄目:編程語言

本篇內容主要講解“Python編程技巧有哪些”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Python編程技巧有哪些”吧!

1、變量值互換

a = 0b = 1a,b = b, a

2、連續(xù)賦值

a, b = 2, 1

3、自動解包賦值

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 = False

8、字典合并

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查找列表中出現(xiàn)最多的元素

a = [1,2,3,3,0]from collections import Counterb = Counter(a)b.most_common(1)[(3, 2)]  # 3出現(xiàn)的次數(shù)最多,為2次

14、賦值表達式,:=,可以將變量賦值和表達式放在一行

import res ="helloworld"match = re.search('o', s)if match:    num = match.group(0)else:    num = Nonenum

3和4可以合并為一行代碼

if match := re.search('o', s):num = match.group(0)else:num = None

15、isintance函數(shù)用來判斷實例的類型

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、查找列表中出現(xiàn)次數(shù)最多的數(shù)字

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、列表負數(shù)索引

a[-2]'domi'

接著昨天的分享寫,昨天的鏈接為:Python編程特殊小技巧匯集(一)

21、列表切片,

a = [1,2,3,'domi','mi']>>> a[2:4]  # 提取第3個位置到第5個位置(不包含第5個位置)的數(shù)據(jù)[3, 'domi']>>> a[:3] # 提取前3個數(shù)據(jù)[1, 2, 3]>>> a[::2] # 提取偶數(shù)項[1, 3, 'mi']>>> a[1::2] # 提取奇數(shù)項[2, 'domi']>>> a[::-1] # 列表反轉['mi', 'domi', 3, 2, 1]

22、二維數(shù)組轉為一維數(shù)組

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個數(shù)據(jù)為%s' %(index, value))第0個數(shù)據(jù)為d第1個數(shù)據(jù)為o第2個數(shù)據(jù)為m第3個數(shù)據(jù)為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>StopIteration

26、集合推導式

>>> 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]dictionaryprint(dictionary)

30、去除列表中重復元素

my_list = [1,4,1,8,2,8,4,5]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 31

32、匿名函數(shù)

def add(a, b):    return a+b# 等同于add = lambda a,b:a+badd(1,2)

到此,相信大家對“Python編程技巧有哪些”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI