Python map, lambda, with, context manager学习实践

map(fun, iter1, iter2, ....)

map(function, iterable, ...)Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

接收一个函数fun和与fun参数数量相同多的迭代器作为对象,每次在每个迭代器里取一个元素进行fun运算。
Python2返回一个函数执行结果的列表(没试过)
Python3返回一个map类的迭代器,只能遍历一遍的, 例如
>>> def abc(a, b, c):
...     return a*100+b*10+c
...
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> m = map(abc, l1, l2, l3)
>>> m
<map object at 0x00000000027090B8>
>>> for i in m:
...     print(i)
...
147
258
369

lambda

Lambda forms (lambda expressions) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with
等价于
def <lambda>(arguments):
    return expression

简单说就是创建一个匿名函数对象,并且这个函数只能是一句表达式,如
>>> m = lambda x,y,z: (x-y)*z
>>> print(m(3,1,2))
4

Context Manager

Python’s with statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:

#! python 3.3

import sys, os

class RedirectStdoutTo:
    """
    重定向输出到流对象
    实现 __enter__()和 __exit()__方法的类就是一个context manager
    """
    def __init__(self, out_new):
        self.out_new = out_new
        
    def __enter__(self):
        self.out_old = sys.stdout
        sys.stdout = self.out_new
        
    def __exit__(self, *args):
        sys.stdout = self.out_old
        
def dataFormatConvert(fin, fout):
    d = dict()
    pname = ""
    maxX = minX = 117.396814
    maxY = minY = 40.233095
    with open(fin, encoding="gb18030", mode='r') as fa:
        lno = 0
        for line in fa:
            if lno % 2 == 0:
                pname = line.split()[0]
                print(pname)
                if pname not in d:
                    d[pname] = []
            else:
                block = []
	# map产生一个只能运行一起的迭代器
                for item in map(lambda p: [float(s) for s in p.split(',')], line.split(';')):
                    maxX = max(maxX, item[0])
                    maxY = max(maxY, item[1])
                    minX = min(minX, item[0])
                    minY = min(minY, item[1])
                    block.append(item)
                d[pname].append(block)                                
            lno += 1
            
    # 定义lambda函数,把x和y的值从原区间转换到[-1,1]区间
    newX = lambda x: (x-minX)/(maxX-minX)*2 - 1
    newY = lambda y: (y-minY)/(maxY-minY)*2 - 1
    
    # with 关键字后进入一个上下文,封装了进入和离开上下文的细节
    with open(fout, encoding='utf-8', mode='w') as fb, RedirectStdoutTo(fb):
	# 字典类的遍历
        for k,v in d.items():
            print(k, len(v))
            for block in v:
                print(len(block))
	# 列表解析,用str的join()方法把字符串列表合并输出,把io操作减少到只有一次,提高效率
                print('\n'.join([' '.join([str(newX(p[0])), str(newY(p[1]))]) for p in block]))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值