40個 python 奇技淫巧
Python的優(yōu)雅不言而喻,能用一行代碼解決的問題絕不用兩行代碼,這里我給你總結(jié)40個地道的Python代碼技巧。如果你是從其它語言轉(zhuǎn)過來的,你一定會大呼,Python 牛逼,還有這種操作。如果你是剛學編程,你會感覺,這是編程語言該有的樣子。
0、兩個變量值互換
>>> a=1
>>> b=2
>>> a,b=b,a
>>> a
2
>>> b
11、連續(xù)賦值
a = b = c = 502、自動解包
>>> a,b,c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>>
>>>
>>> a, *others = [1,2,3,4]
>>> a
1
>>> others
[2, 3, 4]
>>>4、鏈式比較
a = 15
if (10 < a < 20):
print("Hi")等價于
a = 15
if (a>10 and a<20):
print("Hi")5、重復列表
>>> [5,2]*4
[5, 2, 5, 2, 5, 2, 5, 2]6、重復字符串
>>> "hello"*3
'hellohellohello'7、三目運算
age = 30
slogon = "牛逼" if age == 30 else "niubility"等價于
if age = 30:
slogon = "牛逼"
else:
slogon = "niubility"8、字典合并
>>> a= {"a":1}
>>> b= {"b":2}
>>> {**a, **b}
{'a': 1, 'b': 2}
>>>9、字符串反轉(zhuǎn)
>>> s = "i love python"
>>> s[::-1]
'nohtyp evol i'
>>>10、列表轉(zhuǎn)字符串
>>> s = ["i", "love", "pyton"]
>>> " ".join(s)
'i love pyton'
>>>11、for else 語句
檢查列表foo是否有0,有就提前結(jié)束查找,沒有就是打印“未發(fā)現(xiàn)”
found = False
for i in foo:
if i == 0:
found = True
break
if not found:
print("未發(fā)現(xiàn)")如果用 for else 語法來寫可以省幾行代碼
for i in foo:
if i == 0:
break
else:
print("未發(fā)現(xiàn)")11、字典推導式
>>> m = {x: x**2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>>12、用Counter查找列表中出現(xiàn)最多的元素
>>> content = ["a", "b", "c", "a", "d", "c", "a"]
>>> from collections import Counter
>>> c = Counter(content)
>>> c.most_common(1)
[('a', 3)]
>>>出現(xiàn)第1多的元素是a,一共出現(xiàn)3次, 你也可以用類似的方法找出第二多或者第三多的
13、默認值字典
給字典中的value設置為列表,普通方法
>>> d = dict()
if 'a' not in d:
d['a'] = []
d['a'].append(1)使用defaultdict默認字典構(gòu)建一個初始值為空列表的字典
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)14、賦值表達式
這是3.8的新特性,賦值表達式又成為海象運算符:=, 可以將變量賦值和表達式放在一行,什么意思?看代碼就明白
>>> import re
>>> data = "hello123world"
>>> match = re.search("(\d+)", data) # 3
>>> if match: # 4
... num = match.group(1)
... else:
... num = None
>>> num
'123'第3、4行 可以合并成一行代碼
>>> if match:=re.search("(\d+)", data):
... num = match.group(1)
... else:
... num = None
...
>>> num
'123'15、isinstance
isinstance 函數(shù)可用于判斷實例的類型,其實第二個參數(shù)可以是多個數(shù)據(jù)類型組成的元組。例如:
isinstance(x, (int, float))
# 等價于
isinstance(x, int) or isinstance(x, float)類似的函數(shù)還有字符串的startswith,endswith,例如:
s.startswith(('"""', "'''"))
# 等價于
s.startswith("'''") or s.startswith('"""')16、用 http.server 共享文件
# python3
python3 -m http.server
# python2
python -m SimpleHTTPServer 8000效果如下,可以在瀏覽器共享文件目錄,方便在局域網(wǎng)共享文件
17、zip 函數(shù)實現(xiàn)字典鍵值對互換
>>> lang = {"python":".py", "java":".java"}
>>> dict(zip(lang.values(), lang.keys()))
{'.java': 'java', '.py': 'python'}18、查找列表中出現(xiàn)次數(shù)最多的數(shù)字
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 5]
>>> max(set(test), key=test.count)
419、使用 slots 節(jié)省內(nèi)存
class MyClass(object):
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
print(sys.getsizeof(MyClass))
class MyClass(object):
__slots__ = ['name', 'identifier']
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
print(sys.getsizeof(MyClass))
# In Python 3.5
# 1-> 1016
# 2-> 88820、擴展列表
>>> i = ['a','b','c']
>>> i.extend(['e','f','g'])
>>> i
['a', 'b', 'c', 'e', 'f', 'g']
>>>21、列表負數(shù)索引
>>> a = [ 1, 2, 3]
>>> a[-1]
322、列表切片
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[3:6] # 第3個到第6個之間的元素
[3, 4, 5]
>>> a[:5] # 前5個元素
[0, 1, 2, 3, 4]
>>> a[5:] # 后5個元素
[5, 6, 7, 8, 9]
>>> a[::] # 所有元素(拷貝列表)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::2] # 偶數(shù)項
[0, 2, 4, 6, 8]
>>> a[1::2] # 奇數(shù)項
[1, 3, 5, 7, 9]
>>> a[::-1] # 反轉(zhuǎn)列表
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]23、二維數(shù)組變一維數(shù)組
import itertools
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> i = itertools.chain(*a)
>>> list(i)
[1, 2, 3, 4, 5, 6]24、有索引的迭代
>>> a = ['Merry', 'Christmas ', 'Day']
>>> for i, x in enumerate(a):
... print '{}: {}'.format(i, x)
...
0: Merry
1: Christmas
2: Day25、列表推導式
>>> le = [x*2 for x in range(10)]
>>> le # 每個數(shù)乘以2
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> le = [x for x in range(10) if x%2 == 0]
>>> le # 獲取偶數(shù)項
[0, 2, 4, 6, 8]26、生成器表達式
>>> ge = (x*2 for x in range(10))
>>> ge
at 0x01948A50>
>>> next(ge)
0
>>> next(ge)
2
>>> next(ge)
4
...
>>> next(ge)
Traceback (most recent call last):
File "" , line 1, in
StopIteration 27、集合推導式
Python
>>> nums = {n**2 for n in range(10)}
>>> nums
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}28、判斷key是否存在字典中
>>> d = {"1":"a"}
>>> d['2']
Traceback (most recent call last):
File "" , line 1, in
KeyError: '2'
>>> '1' in d
True
>>> d['1']
'a'
>>> d.get("1")
'a'
>>> d.get("2")
>>>29、裝飾器
from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "<{0}>{1}{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
"""returns some text"""
return "Hello " + name
print(get_text("Python"))
>>>Hello Python
30、字典子集
>>> def sub_dicts(d, keys):
... return {k:v for k, v in d.items() if k in keys}
...
>>> sub_dicts({1:"a", 2:"b", 3:"c"}, [1,2])
{1: 'a', 2: 'b'}31、反轉(zhuǎn)字典
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>>
>>> zip(d.values(), d.keys())
0x019136E8>
>>> z = zip(d.values(), d.keys())
>>> dict(z)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'} 32、具名元組
>>> from collections import namedtuple
>>> Point = namedtuple("Point", "x,y")
>>> p = Point(x=1, y=2)
>>> p.x
1
>>> p[0]
1
>>> p.y
2
>>> p[1]
233、設置字典默認值
>>> d = dict()
>>> if 'a' not in d:
... d['a'] = []
...
>>> d['a'].append(1)
>>> d
{'a': [1]}
>>> d.setdefault('b',[]).append(2)
>>> d
{'a': [1], 'b': [2]}
>>>34、有序字典
>>> d = dict((str(x), x) for x in range(10))
>>> d.keys() # key 無序
dict_keys(['0', '1', '5', '9', '4', '6', '7', '8', '2', '3'])
>>> from collections import OrderedDict
>>> m = OrderedDict((str(x), x) for x in range(10))
>>> m.keys() # key 按照插入的順序排列
odict_keys(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])35、列表中最大最小的前n個數(shù)
>>> import heapq
a = [51, 95, 14, 65, 86, 35, 85, 32, 8, 98]
>>> heapq.nlargest(5,a)
[98, 95, 86, 85, 65]
>>> heapq.nsmallest(5,a)
[8, 14, 32, 35, 51]
>>>36、打開文件
>>> with open('foo.txt', 'w') as f:
... f.write("hello")
...37、兩個列表組合成字典
list_1 = ["One","Two","Three"]
list_2 = [1,2,3]
dictionary = dict(zip(list_1, list_2))
print(dictionary)38、去除列表中重復元素
my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
print(my_list)39、打印日歷
import calendar
>>> print(calendar.month(2021, 1))
January 2021
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 3140、匿名函數(shù)
def add(a, b):
return a+b等價于
>>> add = lambda a,b:a+b
>>> add(1,2)
3還有哪些你認為是奇技淫巧的代碼,歡迎補充,采納者紅包獎勵
歡迎關(guān)注Python之禪
評論
圖片
表情
