zoukankan      html  css  js  c++  java
  • 第17条:在参数上面迭代时,要多加小心

    实验中用的 init.py

    15
    35
    80
    

    def read_visits(data_path):
        with open(data_path) as f:
            for line in f:
                yield int(line)
    
    def normalize_copy(numbers):
        numbers = list(numbers)
        total = sum(numbers)
        result = []
        for value in numbers:
            percent = 100 * value / total
            result.append(percent)
        return result
    
    it = read_visits('__init__.py')
    percentages = normalize_copy(it)
    print(percentages)
    
    输出: 
    [11.538461538461538,26.923076923076923,61.53846153846154]
    
    

    2.传入函数

    def normalize_func(get_iter):
        total = sum(get_iter())
        result = []
        for value in get_iter():#New iterator
            percent = 100 * value / total
            result.append(percent)
        return result
    rcentages = normalize_func(lambda: read_visits('__init__.py'))
    print(percentages)
    

    2. 类的迭代器

    class ReadVisits(object):
        def __init__(self,data_path):
            self.data_path = data_path
    
        def __iter__(self):
            with open(self.data_path) as f:
                for line in f:
                    yield int(line)
    visits = ReadVisits('__init__.py')
    percentages = list(visits)
    print(percentages)
    输出:
    [15, 35, 80]
    

    3.限定必须传入容器对象

    def normalize_defensive(numbers):  
        if iter(numbers) is iter(numbers):  # An iterator -- bad!
            raise TypeError('Must supply a container')
        total = sum(numbers)
        result = []
        for value in numbers:
            percent = 100 * value / total
            result.append(percent)
        return result
    
    visits = [15,35,80]
    normalize_defensive(visits)
    visits = ReadVisits('__init__.py')
    a = normalize_defensive(visits)
    print('a',a)
    输出:a [11.538461538461538, 26.923076923076923, 61.53846153846154]
    
    • 把_iter._方法实现为生成器,即可定义自己的容器类型。
    • 想判断某个值是迭代器还是容器,可以拿该值为参数,两次调用iter函数,若结果相同,则是迭代器,调用内置的next函数,即可令该迭代器前进一步。
    写入自己的博客中才能记得长久
  • 相关阅读:
    css面试题目
    5. React-Router05 BrowserRouter 和hashrouter
    5. React-Router03 withRouter
    5. React-Router01
    CVE-2019-0708—微软RDP远程桌面代码执行漏洞复现
    正则表达式学习汇总
    CTF---PHP安全考题
    快速搭建主动诱导型开源蜜罐框架系统--hfish
    python--爬取网页存在某字符
    Linux 实用指令之查看端口开启情况
  • 原文地址:https://www.cnblogs.com/heris/p/14738535.html
Copyright © 2011-2022 走看看