0. 程序必须先让人读懂,然后才能让计算机执行。
“Programs must be written for people to read, and only incidentally for machines to execute.”
1. 交换赋值
a, b = b, a # 先生成一个元组(tuple)对象,然后unpack
2. Unpacking
a,*c,d = [1,2,3,4,5]
3. 使用操作符in
if 0 in [1,2,3]: print(1)
4. 字符串操作
''.join(['a','b','c'])
5. 字典键值列表
for key in my_dict: # my_dict[key] ...
# 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
# 生成静态的键值列表。
6. 字典键值判断
if key in my_dict: #...do something with d[key]
7. 字典 get 和 setdefault 方法
a = {} # update or create
for (b,c) in ((1,2),(2,3)):
a[b] = a.get(b,0) # if b not in a: a[b]=0
# a.setdefault(b,0)
print(a)
8. 判断真伪
if ['a']: print(1)
9. 遍历列表以及索引
for idx,item in enumerate('a b c'.split()): print(idx,item)
10. 列表推导
[print(i) for i in range(10) if i%2==0]
11. 列表推导-嵌套
a = (i for j in range(200) if j%3==0 \
for i in range(100) if i%3==0)
for b in a: print(b)
12. 循环嵌套
from itertools import product
[print(x,y,z) for x,y,z in product([1,2],[3,4],[5,6])]
13. 尽量使用生成器代替列表
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b # print(b)
a, b = b, a + b
n = n + 1
for n in fab(5): print(n)
14. 使用any/all函数
print(any([False,False]),all([True,True]))
15. 属性(property)
class Goods(object):
def __init__(self):
self.price = 100 # 原价
self.discount = 0.8 # 折扣
def get_price(self):
# 实际价格 = 原价 * 折扣
new_price = self.price * self.discount
return new_price
def set_price(self, value):
self.price = value
def del_price(self):
del self.price
# 获取 设置 删除 描述文档
PRICE = property(get_price, set_price, del_price, '价格属性描述...')
# 使用此方式设置
obj = Goods()
print(obj.PRICE) # 获取商品价格
obj.PRICE = 200 # 修改商品原价
print(obj.PRICE)
del obj.PRICE # 删除商品原价
16. 使用 with 处理文件打开
with open("some_file.txt") as f: data = f.read()
17. 使用 with 处理加锁
import threading
lock = threading.Lock()
with lock: # 互斥操作...
# lock.acquire()
# try: # 互斥操作...
# finally: lock.release()
18. *Build-in Functions *内置函数
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
abs() | delattr() | hash() | memoryview() | set() |
all() | dict() | help() | min() | setattr() |
any() | dir() | hex() | next() | slice() |
ascii() | divmod() | id() | object() | sorted() |
bin() | enumerate() | input() | oct() | staticmethod() |
bool() | eval() | int() | open() | str() |
breakpoint() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | __import__() |
complex() | hasattr() | max() | round() |
# string functions
# str.rpartition()
print('str.rpartition','django.contrib.db'.rpartition(".")[-2:])
# str.isidentifier()
print('obj.isidentifier() is string','django'.isidentifier(),'0'.isidentifier())
# str.replace(a,b)
print('replaced'.replace("d",""))
# str.split(a)
print('split split'.split(" "))
# Object Oriented
class Test:
a = None
def __init__(self): self.a = True
def __repr__(self): return '__repr__ return class'
def __str__(self): return '__str__ packed repr for endusers'
#
def hasattr(self): return(hasattr(self,'a'),hasattr(self,'b'))
@property
def method_with_property(self): return 'method_with_property'
def method_without_property(self): return 'method_without_property()'
# class >> __new__
test = object.__new__(Test)
# class >> __repr__ >> __str__
print(test)
print(test.__repr__())
print(test.__str__())
# class >> getattr(self,'a')
print('getattr a:%s' % getattr(test,'a'))
# class >> hasattr(self,'b')
print('hasattr b:%s' % hasattr(test,'b'))
# class >> __init__ >> __dict__
print('__dict__',test.__dict__,test.a)
test.__init__()
print('__dict__',test.__dict__,test.a)
# class >> @property
print(test.method_with_property)
print(test.method_without_property())
# map() 会根据提供的函数对指定序列做映射
print(list(map(lambda x: x * x, list(range(10)))))
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。