zoukankan      html  css  js  c++  java
  • 三小时快速入门Python第五篇--异常处理与迭代器

    异常处理与迭代器

    1、异常处理

     1 # 使用 try/except 代码块来处理异常
     2 # 自 Python 2.6 以上版本支持:
     3 try:
     4     # 使用 "raise" 来抛出一个异常
     5     raise IndexError("This is an index error")
     6 except IndexError as e:
     7     pass    # Pass 表示无操作. 通常这里需要解决异常.
     8 except (TypeError, NameError):
     9     pass    # 如果需要多个异常可以同时捕获
    10 else:   # 可选项. 必须在所有的except之后
    11     print("All good!")   # 当try语句块中没有抛出异常才会执行
    12 finally: # 所有情况都会执行
    13     print("We can clean up resources here")
    14 
    15 # with 语句用来替代 try/finally 简化代码
    16 with open("myfile.txt") as f:
    17     for line in f:
    18         print (line)

    2、迭代器

     1 # Python提供了一个称为Iterable的迭代器。
     2 # iterable是可以作为序列处理的对象。
     3 # 返回范围函数的对象是iterable。
     4 
     5 filled_dict = {"one": 1, "two": 2, "three": 3}
     6 our_iterable = filled_dict.keys()
     7 print(our_iterable)  # => dict_keys(['one', 'two', 'three']). 这个是实现了迭代器接口的一个对象.
     8 
     9 # 我们可以循环遍历.
    10 for i in our_iterable:
    11     print(i)  # 输出为: one, two, three
    12 
    13 # 然而我们并不能通过下标进行访问 所以要用迭代器来进行访问
    14 our_iterable[1]  # 会报错 Raises a TypeError
    15 
    16 # An iterable is an object that knows how to create an iterator.
    17 # 定义一个名字叫our_iterator的迭代器,实际上有点类似于指针,指向 our_iterable 这个的第一个元素
    18 our_iterator = iter(our_iterable)
    19 
    20 # Our iterator is an object that can remember the state as we traverse through it.
    21 # We get the next object with "next()".
    22 # 获取这个迭代器所指的值 用next 输出后 our_iterator 指向下一个元素
    23 next(our_iterator)  # => "one"
    24 
    25 # It maintains state as we iterate.
    26 # 继续迭代
    27 next(our_iterator)  # => "two"
    28 next(our_iterator)  # => "three"
    29 
    30 # After the iterator has returned all of its data, it gives you a StopIterator Exception
    31 # 迭代结束
    32 next(our_iterator)  # Raises StopIteration
    33 
    34 # You can grab all the elements of an iterator by calling list() on it.
    35 # 可以将这个强制转换成list
    36 list(filled_dict.keys())  # => Returns ["one", "two", "three"]

     上一篇:三小时快速入门Python第四篇--函数与对象

     下一篇:三小时快速入门Python终结篇--其他模块导入

  • 相关阅读:
    Android游戏开发:游戏框架的搭建(4)
    Android游戏开发:游戏框架的搭建(2)
    android之HttpURLConnection
    Android游戏开发:游戏框架的搭建(3)
    Socket连接与HTTP连接
    Java初级优化
    Android文件操作总结
    android GC内存泄露问题
    Java高级优化技术
    JAVA中三种URL连接方法
  • 原文地址:https://www.cnblogs.com/xwxz/p/13359312.html
Copyright © 2011-2022 走看看