我是芒果!
這篇是專門蒐集各種簡單的小技巧.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})
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
>>> 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 (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()
a and b
a & b
# =======
a or b
a | b
Python
tips & tricks
Copyright © 2022 Mango-Bot-Factory. All rights reserved.
簡單列出Python大部分的魔術方法(Magic Method)
Dec 27, 2023https://memes.tw/developers
Dec 4, 2022[TOC] 原文 意思 翻譯 備註 PR / MR Pull / Merge Request 合併請求
Jul 15, 2022[TOC] Copyright © 2022 Mango-Bot-Factory. All rights reserved. {%hackmd @Luminous-Coder/dark-theme %}
Jul 14, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up