long_winded_computation = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 +
13 + 14 + 15 + 16 + 17 + 18 + 19 + 20)
from random import random,uniform,randrange
def double (x):
return x*2
def apply_to_one(f):
return f(1)
my_double = double # 指向之前定义的函数(可以将函数作为对象赋给其他变量)
x = apply_to_one(my_double) # 等于2。
word_counts = Counter(document)
for word, count in word_counts.most_common(10):
print word, count
x = None
print x == None # 打印True,但这并非Python的惯用法
print x is None # 打印True,符合Python的惯用法
is比较两个变量所指对象的内容和地址是否相同,==只比较内容
具体参考:https://blog.csdn.net/qq_26442553/article/details/82195061
pairs = [(x, y)
for x in range(10)
for y in range(10)] # 100个对(0,0) (0,1) ... (9,8), (9,9)
#其中后面的 for 语句可以使用前面的 for 语句的结果
生成器返回值是一个迭代器:具体可参考:https://www.runoob.com/python3/python3-iterator-generator.html
re.match(), re.search(), re.split(), re.sub()
import re
print all([ # 所有这些语句都为true,因为
not re.match("a", "cat"), # * 'cat'不以'a'开头
re.search("a", "cat"), # * 'cat'里有一个字符'a'
not re.search("c", "dog"), # * 'dog'里没有字符'c'
3 == len(re.split("[ab]", "carbs")), # * 分割掉a,b,剩余长度为3
"R-D-" == re.sub("[0-9]", "-", "R2D2") # 用虚线进行位的替换
] # 打印True
具体参考:https://www.runoob.com/python/python-reg-expressions.html
from functools import partial
partial()函数可对已有函数进行改造,使其可以接受部分参数。例如:
from functools import partial
def exp(base, power):
return base ** power
two_to_the = partial(exp, base=2) # 现在是一个包含一个变量的函数
print two_to_the(3) # 8
另外map(),reduce(), filter() 均返回迭代器(map:映射,reduce: 缩小, filter:过滤器)。用法如下:
均为:第一个参数为函数,第二个参数为序列
def double(x):
return 2 * x
xs = [1, 2, 3, 4]
twice_xs = [double(x) for x in xs] # [2, 4, 6, 8]
twice_xs = list(map(double, xs)) # 和上面一样
def is_even(x):
return x % 2 == 0
x_evens = [x for x in xs if is_even(x)] # [2, 4]
x_evens = list(filter(is_even, xs)) # 和上面一样
from functools import reduce #reduce()已经移入了functools内置模块
def multiply(x, y):
return x * y
x_product = reduce(multiply, xs) # = 1 * 2 * 3 * 4 = 24
list_product = partial(reduce, multiply) # reduce了一个列表的*function*
x_product = list_product(xs) # 同样是24
for i, document in enumerate(documents): #documents是一个列表
do_something(i, document)
zip()返回值也为iteration,其中每个元素是一个tuple,参数可以是多个iteration不仅限于列表。
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
zip(list1, list2) # 是[('a', 1), ('b', 2), ('c', 3)]
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(*pairs) # zip() 和zip(*)相当于逆操作
def f2(x, y):
return x + y
def doubler_correct(f):
# works no matter what kind of inputs f expects
def g(*args, **kwargs):
# whatever arguments g is supplied, pass them through to f
return 2 * f(*args, **kwargs)
return g
g = doubler_correct(f2)
print(g(1, 2)) # 6