其他
Python 三十大实践、建议和技巧
if not sys.version_info > (2, 7):
# berate your user for running a 10 year
# python version
elif not sys.version_info >= (3, 5):
# Kindly tell your user (s)he needs to upgrade
# because you're using 3.5 features
%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]
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
def get_user(id):
# fetch user from database
# ....
return name, birthdate
name, birthdate = get_user(4)
数据类需要至少一定数量的代码
可以通过 __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')
a = 1
b = 2
a, b = b, a
print (a)
# 2
print (b)
# 1
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
# {'a': 1, 'b': 3, 'c': 4}
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']
mylist = ['The', 'quick', 'brown', 'fox']
mystring = " ".join(mylist)
print(mystring)
# 'The quick brown fox'
pip3 install emoji
import emoji
result = emoji.emojize('Python is :thumbs_up:')
print(result)
# 'Python is 👍'
# You can also reverse this:
result = emoji.demojize('Python is 👍')
print(result)
# 'Python is :thumbs_up:'
a[start:stop:step]
start:0
stop:列表的末尾
step:1
# We can easily create a new list from
# the first two elements of a list:
first_two = [1, 2, 3, 4, 5][0:2]
print(first_two)
# [1, 2]
# And if we use a step value of 2,
# we can skip over every second number
# like this:
steps = [1, 2, 3, 4, 5][0:5:2]
print(steps)
# [1, 3, 5]
# This works on strings too. In Python,
# you can treat a string like a list of
# letters:
mystring = "abcdefdn nimt"[::2]
print(mystring)
# 'aced it'
revstring = "abcdefg"[::-1]
print(revstring)
# 'gfedcba'
revarray = [1, 2, 3, 4, 5][::-1]
print(revarray)
# [5, 4, 3, 2, 1]
pip3 install Pillow
from PIL import Image
im = Image.open("kittens.jpg")
im.show()
print(im.format, im.size, im.mode)
# JPEG (1920, 1357) RGB
map(function, something_iterable)
def upper(s):
return s.upper()
mylist = list(map(upper, ['sentence', 'fragment']))
print(mylist)
# ['SENTENCE', 'FRAGMENT']
# Convert a string representation of
# a number into a list of ints.
list_of_ints = list(map(int, "1234567")))
print(list_of_ints)
# [1, 2, 3, 4, 5, 6, 7]
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
print (set(mylist))
# {1, 2, 3, 4, 5, 6}
# And since a string can be treated like a
# list of letters, you can also get the
# unique letters from a string this way:
print (set("aaabbbcccdddeeefff"))
# {'a', 'b', 'c', 'd', 'e', 'f'}
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
# 4
max()将返回列表中的最大值。key参数接受单个参数函数确定定制排序顺序,在本例中,它是test.count,该函数应用于iterable对象中的每个元素。
.count()是列表的一个内建函数,该函数接收一个参数,并计算该参数的出现次数。因此在本例中,test.count(1)返回2,testcount(4)返回4。
set(test)返回test列表中的所有唯一值,因此是{1,2,3,4}。
pip3 install progress
from progress.bar import Bar
bar = Bar('Processing', max=20)
for i in range(20):
# Do some work
bar.next()
bar.finish()
In [1]: 3 * 3
Out[1]: 9
In [2]: _ + 3
Out[2]: 12
python3 -m http.server
23、多行字符串
s1 = """Multi line strings can be put
between triple quotes. It's not ideal
when formatting your code though"""
print (s1)
# Multi line strings can be put
# between triple quotes. It's not ideal
# when formatting your code though
s2 = ("You can also concatenate multiple\n" +
"strings this way, but you'll have to\n"
"explicitly put in the newlines")
print(s2)
# You can also concatenate multiple
# strings this way, but you'll have to
# explicitly put in the newlines
[on_true] if [expression] else [on_false]
x = "Success!" if (y == 2) else "Failed!"
from collections import Counter
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
c = Counter(mylist)
print(c)
# Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})
# And it works on strings too:
print(Counter("aaaaabbbbbccccc"))
# Counter({'a': 5, 'b': 5, 'c': 5})
x = 10
# Instead of:
if x > 5 and x < 15:
print("Yes")
# yes
# You can also write:
if 5 < x < 15:
print("Yes")
# Yes
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
pip3 install python-dateutil
from dateutil.parser import parse
logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'
timestamp = parse(log_line, fuzzy=True)
print(timestamp)
# 2020-01-01 00:00:01
# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
Python 3
5 / 2 = 2.5
5 // 2 = 2
pip install chardet
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0
(*本文为AI科技大本营编译文章,转载请微信联系1092722531)
◆
精彩推荐
◆
点击阅读原文,或扫描文首贴片二维码
所有CSDN 用户都可参与投票活动
加入福利群,每周还有精选学习资料、技术图书等福利发送
点击投票页面「讲师头像」,60+公开课免费学习
只需3行代码自动生成高性能模型,支持4项任务,亚马逊发布开源库AutoGluon
AbutionGraph:构建以知识图谱为核心的下一代数据中台
想知道与你最般配的伴侣长什么样?这个“夫妻相”生成器要火
2020年趋势一览:AutoML、联邦学习、云寡头时代的终结
达摩院 2020 预测:感知智能的“天花板”和认知智能的“野望”
十大新兴前端框架大盘点
联盟链走向何方
拿下微软、Google、Adobe,印度为何盛产科技圈 CEO?
你点的每个“在看”,我都认真当成了AI