1. 程式人生 > >阿里大牛分享的 Python 開發中那些高階技巧

阿里大牛分享的 Python 開發中那些高階技巧

我總結了一些常見的技巧在這裡,可能談不上多高階,但掌握這些至少可以讓你的程式碼看起來 Pythonic 一點。如果你還在按照類C語言的那套風格來寫的話,在 code review 恐怕會要被吐槽了。

列表推導式

>>> chars = [ c for c in 'python' ]
>>> chars
['p', 'y', 't', 'h', 'o', 'n']

字典推導式

>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> double_dict1 = {k:v*2 for (k,v) in dict1.items()}
>>> double_dict1
{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}

集合推導式

>>> set1 = {1,2,3,4}
>>> double_set = {i*2 for i in set1}
>>> double_set
{8, 2, 4, 6}

合併字典

>>> x = {'a':1,'b':2}
>>> y = {'c':3, 'd':4}
>>> z = {**x, **y}
>>> z
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

複製列表

>>> nums = [1,2,3]
>>> nums[::]
[1, 2, 3]
>>> copy_nums = nums[::]
>>> copy_nums
[1, 2, 3]

反轉列表

>>> reverse_nums = nums[::-1]
>>> reverse_nums
[3, 2, 1]

 PACKING / UNPACKING

變數交換

>>> a,b = 1, 2
>>> a ,b = b,a
>>> a
2
>>> b
1

高階拆包

>>> a, *b = 1,2,3
>>> a
1
>>> b
[2, 3]

或者

>>> a, *b, c = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

函式返回多個值(其實是自動packing成元組)然後unpacking賦值給4個變數

>>> def f():
...     return 1, 2, 3, 4
...
>>> a, b, c, d = f()
>>> a
1
>>> d
4

列表合併成字串

>>> " ".join(["I", "Love", "Python"])
'I Love Python'

鏈式比較

>>> if a > 2 and a < 5:
...     pass
...
>>> if 2<a<5:
...     pass

yield from

# 沒有使用 field from
def dup(n):
    for i in range(n):
        yield i
        yield i

# 使用yield from
def dup(n):
    for i in range(n):
    yield from [i, i]

for i in dup(3):
    print(i)

>>>
0
0
1
1
2

in 代替 or

>>> if x == 1 or x == 2 or x == 3:
...     pass
...
>>> if x in (1,2,3):
...     pass

字典代替多個if else

def fun(x):
    if x == 'a':
        return 1
    elif x == 'b':
        return 2
    else:
        return None

def fun(x):
    return {"a": 1, "b": 2}.get(x)

有下標索引的列舉

>>> for i, e in enumerate(["a","b","c"]):
...     print(i, e)
...
0 a
1 b
2 c

生成器

注意區分列表推導式,生成器效率更高

>>> g = (i**2 for i in range(5))
>>> g
<generator object <genexpr> at 0x10881e518>
>>> for i in g:
...     print(i)
...
0
1
4
9
16

預設字典 defaultdict

>>> d = dict()
>>> d['nums']
KeyError: 'nums'
>>>

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["nums"]
[]

字串格式化

>>> lang = 'python'
>>> f'{lang} is most popular language in the world'
'python is most popular language in the world'

列表中出現次數最多的元素

>>> nums = [1,2,3,3]
>>> max(set(nums), key=nums.count)
3

或者
from collections import Counter
>>> Counter(nums).most_common()[0][0]
3

讀寫檔案

>>> with open("test.txt", "w") as f:
...     f.writelines("hello")

判斷物件型別,可指定多個型別

>>> isinstance(a, (int, str))
True

類似的還有字串的 startswith,endswith

>>> "http://foofish.net".startswith(('http','https'))
True
>>> "https://foofish.net".startswith(('http','https'))
True

__str__ 與 __repr__ 區別

>>> "http://foofish.net".startswith(('http','https'))
True
>>> "https://foofish.net".startswith(('http','https'))
True

前者對人友好,可讀性更強,後者對計算機友好,支援 obj == eval(repr(obj))

使用裝飾器

def makebold(f):
return lambda: "<b>" + f() + "</b>"

def makeitalic(f):
return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
return "Hello"

>>> say()
<b><i>Hello</i></b>

不使用裝飾器,可讀性非常差


def say():
return "Hello"

>>> makebold(makeitalic(say))()
<b><i>Hello</i></b>

...此處省略100個高階操作,關注走一波!更多python知識技巧案例持續分享!

推薦一下我的Python的學習裙【 784758214 】,無論你是大牛還是小白,是想轉行還是想入行都可以來了解一起進步一起學習!裙內有開發工具,很多幹貨和技術資料分享!希望新手少走彎路

  不要太過急功近利, 慢慢玩, 精進.

  如果你覺著程式設計有趣, 成長也就不再痛