sum([i for i in range(0,100) if i % 2 ==1])
2.
list(set(lst))
or
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
list(dedupe(lst))
3.
v = ‘abc’
r_v = v[::-1]
4.
def timeit(max_time):
def decorator(func):
def wrapper(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
t1 = time.time()
total = t1-t0
print('"{f_n}" function ran for {total}'.format(f_n=func.__name__, total=total)
if total > max_time:
print('"{f_n}" function exceeds max_time'.format(f_n=func.__name__)
return result
return wrapper
return decorator
class InterInt(object):
def init(self):
self.a = 1
def __iter__(self):
return self
def next(self):
self.a += 1
return self.a - 1
import collections
class CustomDict(collections.UserDict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def __contains__(self, key):
return str(key) in self.data
def __setitem__(self, key, item):
self.data[str(key)] = item
def __getattr__(self, key):
return self.data[str(key)]
if name == ‘main’:
cd = CustomDict(((‘a’, 1), (‘b’, 2)))
print(cd['a'])
print(cd['b'])
7.迭代器和生成器的区别
https://zhuanlan.zhihu.com/p/341439647