In [ ]:
import inspect
from collections.abc import Container
import logging as Log
Log.basicConfig(format='%(asctime)s %(message)s', level=Log.INFO)
In [1]:
nums = [1, 2, 3, 4, 5]
s = sum(x * x for x in nums)
In [2]:
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
nu = dedupe(a, key=lambda d: (d['x'],d['y']))
list(nu)
Out[2]:
In [1]:
def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
In [376]:
# fron logging
class Node(object):
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
# Log.info('__iter__{}'.format(self._children))
return iter(self._children)
def depth_first(self):
yield self
for s in self: # in self 会触发self.__iter__() 获取迭代对象
yield from s.depth_first()
In [377]:
root = Node(0)
child_1 = Node(1)
child_2 = Node(2)
child_3 = Node(3)
child_4 = Node(4)
root.add_child(child_1)
root.add_child(child_2)
child_1.add_child(child_3)
child_1.add_child(child_4)
child_4.add_child(child_3)
# iter(root.depth_first())
# root.depth_first()
for c in root.depth_first():
Log.info(c)
In [371]:
class Cont(object):
def __init__(self, start, end):
self._start = start
self._end = end
self.lst = []
# self.center = self._start
def __iter__(self):
Log.info('iter going: {}'.format(self._start))
return self
def __next__(self):
if self._start == self._end:
raise StopIteration
yield self._start
self._start += 1
if self._start == self._end:
raise StopIteration
# self._start += 1
# return self._start
def __reversed__(self):
n = self._end
while n >= self._start:
yield n
n -= 1
cc = Cont(3,6)
In [ ]:
# ff= iter(cc)
# for rr in Cont(3,6):
# Log.info('for {}'.format(rr))
In [ ]:
class squares:
def __init__(self, start, stop):
self.flag = start - 1
self.value = self.flag
self.stop = stop
def __iter__(self):
# self.value = self.flag
return self
def __next__(self):
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value
a = squares(1,5)
b = squares(1,5)
s = 0
while s<=41:
for i in a:
s= s + i
print(s)
In [2]:
from collections.abc import Container
isinstance('', Container)
Out[2]: