Open yqfang opened 7 years ago
搞 python 的模块引入快一天了(一直在用 node 的思维定式在思考python的模块化)。 遇到我本来以为很简单的事情: https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python https://stackoverflow.com/questions/6465549/import-paths-the-right-way
总结来说也就几句话的事情:
『functional programming python』书中有一段话:Using comprehensions is often a way both to make code more com‐ pact and to shift our focus from the “how” to the “what.” 其实的 what 是指『如何用一堆逻辑去构造一个数据集合』,how 是指:『这个集合由什么构成』
A compre‐ hension is an expression that uses the same keywords as loop and conditional blocks, but inverts their order to focus on the data rather than on the procedure. 这个其实就是函数式编程的思想。
列如下面这段代码是我们习以为常的代码风格:
collection = list()
for datum in data_set:
if condition(datum):
collection.append(datum)
else:
new = modify(datum)
collection.append(new)
用了列表表达式后是这样的:
collection = [d if condition(d) else modify(d) for d in data_set]
Far more important than simply saving a few characters and lines is the mental shift enacted by thinking of what collection is, and by avoiding needing to think about or debug “What is the state of collection at this point in the loop?”
python 2.6 中 set comprehensive 和 dict comprehensive 有点瓜三
map = {'hello': 1, 'word': 2}
反转map:
flapped_map = dict((value, key) for key, value in map.items() )
把 hello 写入集合
sett = set(c for c in 'hello')
Generator comprehensions have the same syntax as list comprehen‐ sions, but they are also lazy. That is to say that they are merely a description of how to get the data that is not realized until one explicitly asks for it, either by calling .next() on the object, or by looping over it. This often saves memory for large sequences and defers computation until it is actually needed. For example:
log_lines = (line for line in read_line(huge_log_file) if complex_condition(line))
直接看这篇文章吧,多看几遍就明白了:
iterable 类 有 iter 方法用于返回对应的 iterator, iterator 有 next 方法;for .. in 实际上去调用 iterable 的 iter 方法找到对应的 iterator 后调用 next 去迭代出结果。
iterable iter 如果返回本身,那么 iterable 本身也是 iterator ,必然有 next 方法,但是 如果调用 list(iterable) 就会 consume 调内部的元素,如果 iter 返回另外一个 iterator ,就不会存在这个问题