30 个 Python 的最佳实践、小贴士和技巧!
作者 | Erik-Jan van Baaren 译者 | 弯月,责编 | 屠敏 出品 | CSDN(ID:CSDNnews)
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代码的时间
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__ 方法
调试的时候,你可以轻松地输出数据类,因为数据类还提供了 __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
end:字符串的结尾
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。该函数会应用于迭代对象的每一项。
test.count 是 list 的内置函数。它接受一个参数,而且还会计算该参数的出现次数。因此,test.count(1) 将返回2,而 test.count(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]: 9In [2]: _ + 3
Out[2]: 12
python3 -m http.server
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
评论