一例生成器sample
举例
def underscore_to_camelcase(s):
def camelcase():
yield str.lower
while True:
yield str.capitalize
return ''.join(f(sub) for sub, f in zip(s.split('_'), camelcase()))
拆解
from collections.abc import Iterator
def underscore_to_camelcase(s):
def camelcase(): # 生成器函数
yield str.lower
while True:
yield str.capitalize
generator_functions_call_result = camelcase()
print(type(generator_functions_call_result)) # <class 'generator'>
zipped = zip(s.split('_'), generator_functions_call_result)
print(isinstance(zipped, Iterator)) # True, 返回的是迭代器对象, 下面f in zipped是最好的证明
result = (f(sub) for sub, f in zipped) # 生成器表达式, f为高阶函数
print(type(result)) # <class 'generator'>
return ''.join(result)
print(underscore_to_camelcase("where_are_you"))
- camelcase是生成器函数,返回str.lower, str.capitalize, str.capitalize ...
- camelcase()是返回了一个生成器(是迭代器的一种特殊类型)
- zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的(迭代器)对象, 是惰性的(python2中返回的是List对象)
- 列表推导式 vs 生成器表达式: 前者是[]后者是()
这样拆分以后就没有那么magic了.