目录 1.可迭代对象 2.迭代器 3.生成器(4个例子) 可迭代对象
# -*- coding: utf-8 -*-
def is_iterable(param):
try:
iter(param)
return True
except TypeError:
return False
params = [1234, '1234', [1, 2, 3, 4], set([1, 2, 3, 4]),
{1:1, 2:2, 3:3, 4:4},
(1, 2, 3, 4)]
for i in params:
print('{} is iterable? {}'.format(i, is_iterable(i)))
1234 is iterable? False
1234 is iterable? True
[1, 2, 3, 4] is iterable? True
{1, 2, 3, 4} is iterable? True
{1: 1, 2: 2, 3: 3, 4: 4} is iterable? True
(1, 2, 3, 4) is iterable? True
[Finished in 0.3s]
# 声明一个迭代器
[i for i in range(10)]
# 声明一个生成器
(i for i in range(10))
# eg.对比迭代器与生成器
import os
import psutil
# 显示当前 py 占内存大小
def show_memory_info(hint):
pid = os.getpid()
p = psutil.Process(pid)
info = p.memory_full_info()
memory = info.uss / 1024. / 1024
print('{} memory used: {} MB'.format(hint, memory))
def test_iterator():
show_memory_info('initing iterator')
list_1 = [i for i in range(100000000)]
show_memory_info('after iterator initated')
print(sum(list_1))
show_memory_info('after sum called')
def test_generator():
show_memory_info('initing generator')
list_2 = (i for i in range(100000000))
show_memory_info('after generator initiated')
print(sum(list_2))
show_memory_info('after sum called')
%time test_iterator()
%time test_generator()
--------***割***---------
initing iterator memory used: 143.48828125 MB
after iterator initated memory used: 4029.390625 MB
4999999950000000
after sum called memory used: 4029.390625 MB
Wall time: 19.6 s
initing generator memory used: 143.7265625 MB
after generator initiated memory used: 143.7265625 MB
499999999500000000
after sum called memory used: 143.70703125 MB
Wall time: 15.8s
# eg.验证 (1+2+3+。。。+n)^2 = 1^3 + 2^3 + 3^3 + ... + n^3
def generator(k):
i = 1
while True:
yield i ** k
i += 1
gen_1 = generator(1)
gen_3 = generator(3)
print(gen_1)
print(gen_3)
<generator object generator at 0x0000000108B6B8B8>
<generator object generator at 0x0000000108B6B930>
def get_sum(n):
sum_1, sum_3 = 0, 0
for i in range(n):
next_1 = next(gen_1)
next_3 = next(gen_3)
print('next_1 = {}, next_3 = {}'.format(next_1, next_3))
sum_1 += next_1
sum_3 += next_3
print(sum_1 * sum_1, sum_3)
get_sum(8)
next_1 = 1, next_3 = 1
next_1 = 2, next_3 = 8
next_1 = 3, next_3 = 27
next_1 = 4, next_3 = 64
next_1 = 5, next_3 = 125
next_1 = 6, next_3 = 216
next_1 = 7, next_3 = 343
next_1 = 8, next_3 = 512
1296 1296
# 给定一个list和一个数字,确认数字是否在list中
# 在此之前使用list.index(x)实现
def index_generator(L, target):
for i, num in enumerate(L):
if num == target:
yield i
print(list(index_generator([1, 6, 2, 4, 5, 2, 4, 7, 2, 8], 2)))
[2, 5, 8]
# 贪心算法:验证一个序列是另一个序列的子序列
def is_subsequence(a, b):
b = iter(b)
return all(i in b for i in a)
print(is_subsequence([1, 3, 5], range(6)))
print(is_subsequence([1, 4, 3], range(6)))
----***----
True
False
# (i in b)等价于
while True:
val = next(b)
if val == b:
yield True
# all函数,当一个迭代器的元素全为True时返回True