python学习日记(2)

    • 切片
    • 迭代
      • 判断是否可迭代
      • 下标循环
    • 列表生成
    • 生成器
      • 自己写生成器

切片

list[begin, end, step]
#end是不包括的

迭代

  • 循环dictionary
for key in dictionary:
    print(key)

for value in dictionary.values():
    print(value)

for key, value in dictionary.items():
    print(key, value)

判断是否可迭代

from collections import Iterable
isinstance("abc", Iterable)

下标循环

for indice, value in enumerate(['a','b','c']):
    print(indice,value)

列表生成

[ n * n for n in range(1, 11) if n % 2 == 1]
[m + n for m in "abc" for n in "def"]

生成器

generator = (n * n for n in range(10next(generator)
#超出范围返回StopIteration错误

自己写生成器

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
         yield b
         a, b = b, a+b
         n = n + 1
    return "done"

你可能感兴趣的:(我的学习日记,python)