Python Tips & Tricks

我是芒果!
這篇是專門蒐集各種簡單的小技巧.w.

限定範圍

if n > 100: n = 100 n = min(n, 100) #============== if n < 0: n = 0 n = max(n, 0)

回傳函數本身

def rFunc(func): def wrapper(*args, **kwargs): return lambda: func(*args, **kwargs) return wrapper

動態生成類

class Foo: def __init__(self): self.a = 1 self.b = lambda: 2 type("Foo", (object,), {"a": 1, "b": lambda: 2})

C++ or Python?

class Cout: def __lshift__(self, other): print(other, end="") return self endl = "\n" cout = Cout() cout << "111" << 222 << endl

以值排序字典

obj: dict = {} dict(sorted(obj.items(), key=lambda x: x[1]))

列表/集合/字典/生成器 表達式

# 列表表達式 list = [item for item in iterable if 條件] list = [] for item in iterable: if 條件: list.append(item) # 集合表達式 {item for item in iterable if 條件} set = set() for item in iterable: if 條件: set.add(item) # 字典表達式 {key: value for key, value in iterable if 條件} dict = {} for key, value in iterable: if 條件: dict[key] = value # 生成器表達式 (item for item in iterable if 條件) def generator(): for item in iterable: if 條件: yield item generator = generator()

內建文檔

>>> def foo(): >>> """title >>> description >>> """ ... >>> help(foo) Help on function foo in module __main__: foo() title description

Python之禪

>>> import this """ The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea let's do more of those! """

if elif else的其他寫法

if (bool): foo() else: bar() (bar, foo)[bool]() # ================ if obj == "a": A() elif obj == "b": B() else: C() {"a": A, "b": B}.get(obj, defalut=C)() match obj: # match-case Python 3.10以上適用 case "a": A() case "b": B() case _: C()

縮短版and or

a and b a & b # ======= a or b a | b

tags: Python tips & tricks

Copyright © 2022 Mango-Bot-Factory. All rights reserved.

HackMD Error: 404 error