編程大神進(jìn)階之路:Python技巧8個(gè)小貼士
↑?關(guān)注 + 星標(biāo)?,每天學(xué)Python新技能
后臺(tái)回復(fù)【大禮包】送你Python自學(xué)大禮包
編輯:技術(shù)君?| 來源:機(jī)器之心
介紹 Python 炫酷功能(例如,變量解包,偏函數(shù),枚舉可迭代對(duì)象等)的文章層出不窮。但是還有很多 Python 的編程小技巧鮮被提及。因此,本文會(huì)試著介紹一些其它文章沒有提到的小技巧,這些小技巧也是我平時(shí)會(huì)用到的的。讓我們一探究竟吧!

user_input?=?"This\nstring?has\tsome?whitespaces...\r\n"
character_map?=?{
????ord('\n')?:?'?',
????ord('\t')?:?'?',
????ord('\r')?:?None
}
user_input.translate(character_map)??#?This?string?has?some?whitespaces...?import?itertools
s?=?itertools.islice(range(50),?10,?20)??#?<itertools.islice?object?at?0x7f70fab88138>
for?val?in?s:
????...string_from_file?=?"""
//?Author:?...
//?License:?...
//
//?Date:?...
Actual?content...
"""
import?itertools
for?line?in?itertools.dropwhile(lambda?line:?line.startswith("http://"),?string_from_file.split("\n")):
????print(line)def?test(*,?a,?b):
????pass
test("value?for?a",?"value?for?b")??#?TypeError:?test()?takes?0?positional?arguments...
test(a="value",?b="value?2")??#?Works...class?Connection:
????def?__init__(self):
????????...
????def?__enter__(self):
????????#?Initialize?connection...
????def?__exit__(self,?type,?value,?traceback):
????????#?Close?connection...
with?Connection()?as?c:
????#?__enter__()?executes
????...
????#?conn.__exit__()?executesfrom?contextlib?import?contextmanager
@contextmanager
def?tag(name):
????print(f"<{name}>")
????yield
????print(f"{name}>")
with?tag("h1"):
????print("This?is?Title.")class?Person:
????__slots__?=?["first_name",?"last_name",?"phone"]
????def?__init__(self,?first_name,?last_name,?phone):
????????self.first_name?=?first_name
????????self.last_name?=?last_name
????????self.phone?=?phoneimport?signal
import?resource
import?os
#?To?Limit?CPU?time
def?time_exceeded(signo,?frame):
????print("CPU?exceeded...")
????raise?SystemExit(1)
def?set_max_runtime(seconds):
????#?Install?the?signal?handler?and?set?a?resource?limit
????soft,?hard?=?resource.getrlimit(resource.RLIMIT_CPU)
????resource.setrlimit(resource.RLIMIT_CPU,?(seconds,?hard))
????signal.signal(signal.SIGXCPU,?time_exceeded)
#?To?limit?memory?usage
def?set_max_memory(size):
????soft,?hard?=?resource.getrlimit(resource.RLIMIT_AS)
????resource.setrlimit(resource.RLIMIT_AS,?(size,?hard))def?foo():
????pass
def?bar():
????pass
__all__?=?["bar"]from?functools?import?total_ordering
@total_ordering
class?Number:
????def?__init__(self,?value):
????????self.value?=?value
????def?__lt__(self,?other):
????????return?self.value?
????def?__eq__(self,?other):
????????return?self.value?==?other.value
print(Number(20)?>?Number(3))
print(Number(1)?5))
print(Number(15)?>=?Number(15))
print(Number(10)?<=?Number(2))原文鏈接:https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fpython-tips-and-trick-you-havent-already-seen-37825547544f
見面禮
掃碼加我微信備注「三劍客」送你上圖三本Python入門電子書
推薦閱讀
點(diǎn)分享 點(diǎn)收藏 點(diǎn)點(diǎn)贊 點(diǎn)在看
評(píng)論
圖片
表情






