Less common Python knowledge

Something unknow or less common Python knowledge

set

集合(Set)是一个无序不重复元素的序列,每个元素只会出现一次。当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合

1
2
3
parame = {value01,value02,...}
或者
set(value)

通过使用集合,你可以测试某些对象的资格或情况,检查它们是否是其它集合的子集,找到两个集合的交集,等等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fruit = {'apple', 'banana', 'orange'}
color = {'yellow', 'blue', 'green'}
print('apple' in fruit)
print('green' in color)

color_copy = color.copy()
print('color is',color)
print('copy color is', color_copy)
# remove 'green',add pink
color_copy.remove('green')
color_copy.add('pink')
print('remove greeen and add pink to color_copy')
print('color is',color)
print('copy color is', color_copy)

print(color & color_copy)
print(color | color_copy)

Output:

1
2
3
4
5
6
7
8
9
True
True
color is {'yellow', 'green', 'blue'}
copy color is {'yellow', 'green', 'blue'}
remove greeen and add pink to color_copy
color is {'yellow', 'green', 'blue'}
copy color is {'yellow', 'pink', 'blue'}
{'yellow', 'blue'}
{'yellow', 'green', 'pink', 'blue'}

text[::-1]

Example

1
2
3
def reverse(text):
return text[::-1]
print(reverse('abcdefg'))

Output

1
gfedcba

Pickle

Python 提供了一个叫作 Pickle 的标准模块,通过它你可以将任何纯 Python 对象存储到一个文件中,并在稍后将其取回。这叫作持久地(Persistently)存储对象
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pickle

# 我们存储相关对象的文件的名称
shoplistfile = 'shoplist.data'
# 我们需要购买的物品清单
shoplist = ['apple', 'mango', 'carrot']

# 准备写入文件
f = open(shoplistfile, 'wb')
# 存储对象至文件--封装(Pickling)
pickle.dump(shoplist, f)
f.close()

# 清除shoplist变量
del shoplist

# 重新打开存储文件
f = open(shoplistfile, 'rb')
# 从文件中载入对象--拆封(Unpickling)
storedlist = pickle.load(f)
print(storedlist)

Output

1
['apple', 'mango', 'carrot']

VarArgs Parameters

有时你可能想定义的函数里面能够有任意数量的变量,也就是参数数量是可变的,这可以通过使用星号来实现
当我们声明一个诸如 *param 的星号参数时,从此处开始直到结束的所有位置参数(Positional Arguments)都将被收集并汇集成一个称为“param”的元组(Tuple)
类似地,当我们声明一个诸如 **param 的双星号参数时,从此处开始直至结束的所有关键字
参数都将被收集并汇集成一个名为 param 的字典(Dictionary)
Example

1
2
3
4
5
6
7
8
9
10
11
def total(a=5, *numbers, **phonebook):
print('a', a)
#遍历元组中的所有项目
for single_item in numbers:
print('single_item', single_item)

#遍历字典中的所有项目
for first_part, second_part in phonebook.items():
print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

Output

1
2
3
4
5
6
7
8
a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None

DocStrings

Python 有一个甚是优美的功能称作文档字符串(Documentation Strings),在称呼它时通常会使用另一个短一些的名docstrings。DocStrings 是一款你应当使用的重要工具,它能够帮助你更好地记录程序并让其更加易于理解
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
print(print.__doc__)

Output

1
2
3
4
5
6
7
8
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

enumerate()函数

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
语法

  • enumerate(sequence, [start=0])
  • 参数
    • sequence 一个序列、迭代器或者其他支持迭代的对象
    • start 下标起始位置
  • 返回值
    返回enumerate(枚举)对象

Example

1
2
3
4
5
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
>[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
1
2
3
4
5
6
7
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print(i, seq[i])
...
0 one
1 two
2 three

all()

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False
元素除了是 0、空、FALSE 外都算 TRUE。
函数等价于:

1
2
3
4
5
def all(iterable):
for element in iterable:
if not element:
return False
return True

语法

  • all(iterable)
  • 参数
    iterable — 元组或列表
  • 返回值
    如果iterable的所有元素不为0、False或者iterable为空,all(iterable)返回True,否则返回False
    注意:空元组、空列表返回值为True,这里要特别注意

filter()

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中
语法

  • filter(function, iterable)
  • 参数
    • function – 判断函数
    • iterable – 可迭代对象
  • 返回值
    返回筛选完的列表

Example

1
2
3
4
5
# 过滤出列表中的所有奇数
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))

Output

1
[1, 3, 5, 7, 9]

判断是容器还是生成器

想要判断某个值是迭代器还是容器,可以拿该值为参数,两次调用iter方法,若结果相同,则是迭代器,调用内置的next方法,即可令迭代器前进一步

1
2
3
def normalize_defensive(numbers):
if iter(numbers) is iter(numbers):
raise TypeError('Must supply a container')

将数值或者列表转换为元组

将数值转换为元组–使用(value,)即可

1
2
3
>>> a = 12
>>> (a,)
(12,)

将列表转换为元组–直接强制转换即可

1
2
3
>>> b = [1,2,3]
>>> tuple(b)
(1, 2, 3)

排序字典

使用内置的方法sorted()方法进行排序
sorted()语法

  • sorted(iterable, *, key=None, reverse=False)

对字典的key和value进行排序

1
2
3
4
5
6
7
>>> a = {'a':2, 'b':1, 'c':5, 'g':4, 'd':10}
# 对key进行排序
>>> sorted(a)
['a', 'b', 'c', 'd', 'g']
# 对value进行排序
>>> sorted(a.values())
[1, 2, 4, 5, 10]

根据字典的value对字典进行排序

1
2
3
4
5
6
# 从小到大,注意排序后的结果是列表,字典key,value被放在元组中
>>> sorted(a.items(), key=lambda x: x[1])
[('b', 1), ('a', 2), ('g', 4), ('c', 5), ('d', 10)]
# 从大到小
>>> sorted(a.items(), key=lambda x: x[1], reverse=True)
[('d', 10), ('c', 5), ('g', 4), ('a', 2), ('b', 1)]

打乱序列

语法

  • random.shuffle(list)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
import random

data = list(range(20))
print(data)

#打乱元素
random.shuffle(data)

>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> random.shuffle(data)
>>> data
[7, 14, 2, 11, 6, 8, 4, 15, 19, 5, 9, 0, 1, 12, 18, 13, 10, 17, 3, 16]

max()方法依据自定义参数获取最大值

max()语法

  • max(iterable, *[, key, default])
  • max(arg1, arg2, *args[, key])

根据字典的value取得字典的最大键和值

1
2
3
4
5
>>> max(a.items(), key=lambda x:x[1])
('d', 10)
# 如果没有指定判断的参数,则默认根据字典的key进行排序
>>> max(a.items())
('g', 4)

判断是否是同一类型

语法

  • isinstance(object, classinfo)

Example

1
2
3
4
5
>>> a = 3
>>> isinstance(a, int)
True
>>> isinstance(a, float)
False

判断是否是子类

语法

  • issubclass(class, classinfo)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> class a():
... pass
...
>>> class b(a):
... pass
...
>>> issubclass(a, b)
False
>>> issubclass(b, a)
True
>>> issubclass(b, b)
True
>>> issubclass(b, object)
True
>>>

对不确定是否存在的字典的键进行赋值

语法

  • setdefault(key[, default])

Example

1
2
3
4
5
>>> a = {}
>>> a.setdefault('b', 1)
1
>>> a
{'b': 1}

本来是这样写的代码

1
2
3
4
5
6
7
8
9
10
11
>>> def count(datas):
... result = {}
... for data in datas:
... if data in result:
... result[data] += 1
... else:
... result[data] = 1
... return result
...
>>> count(data)
{'a': 2, 'b': 2, 'c': 3, 'd': 1}

现在只要这样写就行了

1
2
3
4
5
6
7
8
9
>>> def count(datas):
... result = {}
... for data in datas:
... result.setdefault(data, 0)
... result[data] += 1
... return result
...
>>> count(data)
{'a': 2, 'b': 2, 'c': 3, 'd': 1}

Decorators

装饰器(Decorators)是应用包装函数的快捷方式。这有助于将功能与一些代码一遍又一遍地”包装“。举个例子,我为自己创建了一个retry装饰器,这样我可以将其运用到任何函数之中,如果在一次运行中抛出了任何错误,它就会尝试重新运行,直到最大次数5次,并且每次运行期间都会有一定的延迟。这对于你在对一台远程计算机进行网络调用的情况十分有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from time import sleep
from functools import wraps
import logging

logging.basicConfig()
log = logging.getLogger('retry')

def retry(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
MAX_ATTEMPTS = 5
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return f(*args, **kwargs)
except:
log.exception('Attempt %s/%s failed : %s', attempt, MAX_ATTEMPTS, (args, kwargs))
sleep(10 * attempt)
log.critical('All %s attempts failed : %s', MAX_ATTEMPTS, (args, kwargs))
return wrapped_f

counter = 0

@retry
def save_to_database(arg):
print('Write to a database or make a network call or etc.')
print('This will be automatically retried if exception is thrown.')
global counter
counter += 1
# 这将在第一次调用时抛出异常
# 在第二次运行时将正常工作(也就是重试)
if counter < 2:
raise ValueError(arg)

if __name__ == '__main__':
save_to_database('Some bad value')

字符串补足位数

通常使用的字符串格式化符号{}里面是可以带参数的

  • {:5} 代表此格式化的字符串至少有5位,不足的在字符串前面补充空格
  • {:a>5} 代表此格式化的字符串至少有5位,不足的在字符串前面补充字符a(使用=效果一样)
  • {:a<5} 代表此格式化的字符串至少有5位,不足的在字符串后面补充字符a

Example:

1
2
3
4
5
6
7
8
9
>>> a = 6
>>> '{:5}'.format(a)
' 6'
>>> '{:a>5}'.format(a)
'aaaa6'
>>> '{:a=5}'.format(a)
'aaaa6'
>>> '{:a<5}'.format(a)
'6aaaa'

还可以使用zfill方法进行补足,zfill可以对字符串的左边进行补足,补足元素为0,且在有+-符号时补足元素会在符号之后

1
2
3
4
5
6
>>> a = '43'
>>> a.zfill(5)
'00043'
>>> b = '-43'
>>> b.zfill(5)
'-0043'

获取字符的ASCII码

使用python内置的ord()方法

1
2
3
4
>>> ord('a')
97
>>> ord('A')
65

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×