006. Python入门经典之二: 第九章其它特性和lambda
关于lambda的简单测试
#使用filter函数, 接收一个列表, 并且 可以移除元素 filter_me = [1, 2, 3, 4, 6, 7, 8, 11, 12, 14, 15, 19, 22] #只要返回偶数, lambda在这里创建了一个匿名函数. 可以使用lambda为函数绑定一个名称. 当然该名称只在创建名称的作用域内可以使用 result = filter(lambda x:x%2 == 0, filter_me) print (result) #输出结果: [2, 4, 6, 8, 12, 14, 22] result.append(42) func = lambda x: x%2 == 0 result1 = filter(func, result) print (result) #输出结果: [2, 4, 6, 8, 12, 14, 22, 42]
总结:
lambda只能是简单的函数, 不能包含其他语句, 比如为变量创建名称. 在Lambda内部, 只能执行有限的操作,比如测试相等性, 将两个数相乘, 以特定的方式使用其它已经存在的函数. 但是不能使用if...else之类的结构,lambda主要用在内置函数map和filter中.
map: 短路循环; 特殊的函数, 用于需要对列表中的每个元素执行一个指定的操作的情形. 在实现这种操作时不必写一个循环
#map基本测试: map_me = [1, 2, 3, 4, 6,7 ,8, 11, 12, 14, 15, 19, 22] result = map(lambda x: "这个数字是 %s " % x , map_me) print (result) #输出结果: '\xe8\xbf\x99\xe4\xb8\xaa\xe6\x95\xb0\xe5\xad\x97\xe6\x98\xaf 1 ' 这和书上不一样. 可能书上介绍的是3.1. 我使用的是2.7 #向map中传递列表 map_me_again = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = map(lambda list: [ list[0]], map_me_again) print(result) #输出结果 [[1], [4], [7]] result = map(lambda list: [ list[1]], map_me_again) print(result) #输出结果:[[2], [5], [8]] result = map(lambda list: [ list[1], list[0]], map_me_again) print(result) #输出结果: [[2, 1], [5, 4], [8, 7]] result = map(lambda list: [ list[1]*list[0]], map_me_again) print(result) #输出结果: [[2], [20], [56]] #由上面可以看出map根据lambda指定的方式将列表中的数字重新组合输出, 有点强大
列表解析: 列表解析提供了与结合使用lambda和filter或map相同的功能, 但是由于它可以包含循环和条件语句, 因此能够提供更加强大的能力. 而lambda只允许执行简单的表达式
everything =[1, 2, 3, 4, 6,7 ,8, 11, 12, 14, 15, 19, 22] #输出此列表中的偶数 print ([x for x in everything if x%2 == 0]) #输出结果: [2, 4, 6, 8, 12, 14, 22]
循环迭代器函数 range()
f = range(10,20)
print(f)
#输出结果; [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
for number in range(10):
print("this is nuber %d" , number)
#输出结果; . . .省略一部分. . . ('this is nuber %d', 8) ('this is nuber %d', 9)
for number in range(5, 55, 4):
print ("by fours: %d " % number)
#输出结果; . . .省略一部分. . . by fours: 49 by fours: 53
#检查range迭代器
xr = range(0,10)
print (dir(xr)) #直接调用他不返回列表, 生成一个对它的调用方法的表示
print (xr[0]) #可以模仿数组来调用它
基于字典进行字符串替换(格式化), 一般用于格式化的报表或类似的东西
person = {"name": "James", "camera": "nikon", "handedness": "lefty", "baseball_team": "angels", "instrument": "guitar"}
print("%(name)s, %(camera)s, %(baseball_team)s" % person)
#输出结果: James, nikon, angels
person["height"] = 1.6
person["weight"] = 80
print("%(name)s, %(camera)s, %(baseball_team)s, %(height)2.2f, %(weight)2.2f" % person)
#输出结果: James, nikon, angels, 1.60, 80.00 格式化. 2.2 两位整数两位小数
另一种字符串替换模式
import string #在string模块中; 使用$符作为占位标识符
person = {"name": "James", "camera": "nikon", "handedness": "lefty", "baseball_team": "angels", "instrument": "guitar"}
person["height"] = 1.6
person["weight"] = 80
t = string.Template("$name is $height m high and $weight kilos")
print(t.substitute(person))
#执行结果: James is 1.6 m high and 80 kilos
#字符串模板的第二种使用格式
s = string.Template('There ${moneyType} is ${money}')
print s.substitute(moneyType = 'Dollar',money=12)
# 运行结果显示 There Dollar is 12
import sys
print (sys.argv)
#输出结果: ['C:/Users/LG/Desktop/FirstDemoPython/Kitchen/Python_spe_9.py']当前文件的路径
尝试使用线程
import math
from threading import Thread
import time
class SquareRootCalculator:
"""使用单独的进程计算平方根,并且记录它完成的时间"""
def __init__(self, target):
"""启动计算线程, 并时时检测它是否完成"""
self.results = []
counter = self.CalculatorThread(self, target)
print("Turning on the calculator thread...")
counter.start()
while len(self.results) < target:
print("%d square roots calculated so far." % len(self.results))
time.sleep(1)
print("Calculated %s square root(s); the last one is sqrt(%d)=%f" %
(target, len(self.results), self.results[-1]))
#使用子类负责计算
class CalculatorThread(Thread):
"""负责计算的独立的进程"""
def __init__(self, controller, target):
"""设置守护进程"""
Thread.__init__(self)
self.controller = controller
self.target = target
self.setDaemon(True)
def run(self):
"""计算1和输入参数之间的所有平方根"""
for i in range(1, self.target + 1):
self.controller.results.append(math.sqrt(i))
#调用测试:
SquareRootCalculator(20000)
浙公网安备 33010602011771号