
IPython 基本上是一个增强的shell,仅仅是为了自动补全功能,IPython也是值得使用的,但其实它还有更多作用,包括内建的Magic命令,这里列举了一些:
%cd:改变当前的工作目录; %edit:打开编辑器并在关闭编辑器后执行键入的代码; %env:显示当前的环境变量; %pip:install [pkgs] 在不离开交互式shell的情况下安装功能包; %time 和 %timeit:类似于python中的time模块,可以为代码运行计时。
完整的命令列表参见:
https://ipython.readthedocs.io/en/stable/interactive/magics.html
pip3 install ipython
[ expression for item in list if conditional ]
mylist = [i for i in range(10)]
print(mylist)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def some_function(a):
return (a + 5) / 2
my_formula = [some_function(i) for i in range(10)]
print(my_formula)
# [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
filtered = [i for i in range(20) if i%2==0]
print(filtered)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
通过sys.getsizeof(object)命令可以查看任何对象的内存使用情况:
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# 48
import sys
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632

数据类需要至少一定数量的代码; 可以通过 __eq__ 方法来比较不同的data类对象; 可以 __repr__ 通过很容易地打印一个数据类来进行调试; 数据类需要类型提示,因此减少了 bug。
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
Card(rank='Q', suit='hearts')


mystring = "10 awesome python tricks"
print(mystring.title())
'10 Awesome Python Tricks'
mystring = "The quick brown fox"
mylist = mystring.split(' ')
print(mylist)
# ['The', 'quick', 'brown', 'fox']

pip3 install emoji

更多复杂的例子以及文档,参见:
https://pypi.org/project/emoji/
a[start:stop:step]
start:0
stop:列表的末尾
step:1
pip3 install Pillow

更多资料详见文档:
https://pillow.readthedocs.io/en/stable/
map(function, something_iterable)
map()是一个代替循环的好方式,可以在你的代码中尝试使用map()函数。
max()将返回列表中的最大值。key参数接受单个参数函数确定定制排序顺序,在本例中,它是test.count,该函数应用于iterable对象中的每个元素。 .count()是列表的一个内建函数,该函数接收一个参数,并计算该参数的出现次数。因此在本例中,test.count(1)返回2,testcount(4)返回4。 set(test)返回test列表中的所有唯一值,因此是{1,2,3,4}。
因此在上面的这行语句中我们首先找出了test列表的所有独特值,即{1,2,3,4}。接着,将.count函数应用于set中的每个值,得到一个数量列表,然后通过max找出数量最大的值。
pip3 install progress


In [1]: 3 * 3
Out[1]: 9
In [2]: _ + 3
Out[2]: 12
python3 -m http.server
[on_true] if [expression] else [on_false]
x = "Success!" if (y == 2) else "Failed!"



关于Colorama依赖包的更多信息,参见:
https://pypi.org/project/colorama/
pip3 install python-dateutil
# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
Python 3
5 / 2 = 2.5
5 // 2 = 2
对于这种变化背后的完整动机,可以阅读PEP-0238:
https://www.python.org/dev/peps/pep-0238/
pip install chardet
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0