day21 生成器,列表解析,三元表达式

Python之路,Day9 = Python基础9

判断可迭代对象和迭代器

from collections import Iterable, Iterator # 导入模块功能,用来判断对象是否为Iterable(可迭代对象)、Iterator(迭代器)
isinstance() # 使用这个功能辅助完成判断 isinstance(a, Iterable) 查看a是否为可迭代对象
# 判断对象为可迭代对象还是迭代器


生成器
  生成器就属于迭代器(包含yield的函数)
  yield 可以进行返回值操作,如果后面没有yield拦住,作为返回值,会报错 StopIteration
    def foo():
      print(111)
      yield 1 # 如果打印下面.__next__的结果的话,会打印这个返回值
      print(222)


    f = foo() # 运行这一句的时候,系统不会运行 foo(),而是直接生成一个生成器
    f.__next__()
    f.__next__()


  yield功能:
    说明:在定义函数的时候,如果发现函数中有 yield 那么,在调用的时候,不执行,直接生成 生成器
    1.与 return 类似,都可以返回值,但yield可以多次返回数值
    2.为函数封装好了 __iter__ 和 __next__ 方法
    3.遵循迭代器的取值方式 obj.__next__(), 触发的函数的执行,函数暂停后,通过__next__再继续


列表解析
  # 要求:将 s = 'hello' 放到新列表中
  [i.upper() for i in s] # for 循环得到i,将i作为列表的元素

  # 要求:判断列表 l = [1,31,73,84,57]中的元素, 如果大于30,就将i加入新列表
  res = [i for i in l if i > 30]
      加入字典的值(i)   循环( for i in l )     条件( if i > 30 )

三元表达式
  res = 2 if 2 > 3 else 3     # 正确时执行 判断条件 错误时执行
  print(res)
  结果:3            # 执行结果为 3

=============================homework================

1 编写 tail -f a.txt |grep 'error' |grep '404'命令,周一默写

 1 #! /usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # __author__ = "Always"
 4 # Date: 2017/6/16
 5 
 6 import time
 7 
 8 def tail(file_path):
 9     with open(file_path, encoding='utf-8') as f:
10         f.seek(0,2)
11         while True:
12             line = f.readline()
13             if line:
14                 yield line
15             else:
16                 time.sleep(0.5)
17 
18 def grep(lines, pattern):
19     for line in lines:
20         if pattern in line:
21             yield line
22 
23 
24 g = grep(grep(tail('te.txt'), 'error'), '404')
25 for i in g:
26     print(i)

2 文件a.txt内容
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3

要求使用列表解析,从文件a.txt中取出每一行,做成下述格式
[{‘name’:'apple','price':10,'count':3},{...},{...},...]

3 格式与2一样,但只保留价格大于1000的商品信息

1 print([{'name':i.strip().split()[0], 'price':i.strip().split()[1], 'count':i.strip().split()[2]} for i in open('a.txt')])
2 
3 print([{'name':i.strip().split()[0], 'price':i.strip().split()[1], 'count':i.strip().split()[2]} for i in open('a.txt') if int(i.strip().split()[1]) > 1000])

执行结果

[{'name': 'apple', 'count': '3', 'price': '10'}, {'name': 'tesla', 'count': '1', 'price': '100000'}, {'name': 'mac', 'count': '2', 'price': '3000'}, {'name': 'lenovo', 'count': '3', 'price': '30000'}, {'name': 'chicken', 'count': '3', 'price': '10'}]
[{'name': 'tesla', 'count': '1', 'price': '100000'}, {'name': 'mac', 'count': '2', 'price': '3000'}, {'name': 'lenovo', 'count': '3', 'price': '30000'}]

  

原文地址:https://www.cnblogs.com/alwaysInMe/p/7028155.html