table of Contents
Analytic
Tag (separated by spaces): Python- analytic formula
First, the analysis formula
1, the list of analytical formula
Generating a list of elements 0-9, most self-energizing each element 1, the squaring, returns a list of
# 普通实现 lst = [] for i in range(10): lst.append((i+1)**2) # 列表解析式实现 lst = [(i+1)**2 for i in range(10)]
- grammar
[返回值 for 元素 in 可迭代对象 if 条件]
- Use brackets [], the formula inside
for
loop,if 条件语句可选
- Immediately return a new list
- List analytical formula is syntactic sugar
- Compiler optimization, will not affect the efficiency of shorthand, but because of optimization improves efficiency
- Programmers reduce the workload and reduce errors
- Simplify the code, increase readability
Advanced analytical expression list
- grammar
[expr for i in iterable1 for j in iterable2]
- Equivalent wording:
lst = [] for i in itersble1: for j in iterable2: lst.append((x, y))
- grammar
[expr for i in iterable1 if cond1 if cond2]
- Equivalent wording:
lst = [] for i in itersble1: if cond1: if cond2: lst.append(i) >>> 等价于 for i in iterable1: if cond1 and cond2: lst.append(i)
Exercises
Returns a list of 1-10 square
print([i**2 for i in range(1, 11)])
There is a list lst = [1, 4, 9, 16, 2, 5, 10, 15], generates a new list, new elements is required, and two adjacent the lst
lst = [1, 4, 9, 16, 2, 5, 10, 15] length = len(lst) print([lst[i]+lst[i+1] for i in range(length-1)])
Print multiplication table
[print("{}x{}={:>{}}{}".format(j, i, i*j, 1 if j == 1 else 2, "\n" if i==j else ' '), end="") for i in range(1, 10) for j in range(1, i+1)]
Print ID, left in claim 4 is an integer of 1 starting from the right 10-bit random lowercase letters, separated by an intermediate node; 100 prior to printing
import string from random import choice [print(".".join(["{:0>4}".format(i), "".join(choice(string.ascii_lowercase) for _ in range(10))])) for i in range(100)]
2, a set of analytic formula
grammar
{返回值 for 元素 in 可迭代对象 if 条件}
- List analytic style braces into brackets on it
- Immediately return a collection
usage
{(x, x+1) for x in range(10)}
{for x in range(10)}
# Wrong usage, elements of the collection must be hashed
3, dictionary analysis formula
grammar
{返回值 for 元素 in 可迭代对象 if 条件}
- List analytic style braces into brackets on it
- Use
key:value
the form - Immediately return a dictionary
usage
{x: (x, x+1) for x in range(10)}
{x: [x, x+1] for x in range(10)}
{(x,): [x, x+1] for x in range(10)}
{[x]: [x, x+1] for x in range(10)}
# Wrong usage, not hash{chr(0x41+x): x**2 for x in range(10)}
{str(x): y for i in range(3) for y in range(4)}
Second, the generator expression
1, generator expression syntax
(返回 for 元素 in 可迭代对象 if 对象)
- List analytic formula in parentheses into brackets on it
- Returns a generator (iterables, iterator)
Using the built-in function
next()
to determine whether an object is the generator
using built-in functioniter()
to an object-oriented programming object is a generator
2, examples
# 生成器表达式使用
g = ("{:04}".format(i) for i in range(1, 11))
next(g)
for i in g:
print(i)
print("~~~~~~~~~~~")
for i in g:
print(i)
# 总结
# - 延迟计算
# - 返回一个迭代器,可以迭代
# - 从前到后走完一遍后,不能回头
# 列表生成器
g = ["{:04}".format(i) for i in range(1, 11)]
next(g)
for i in g:
print(i)
print("~~~~~~~~~~~")
for i in g:
print(i)
# 总结
# - 立即计算
# - 返回的不是一个迭代器,而是一个可以迭代对象列表
# - 从前到后走完一遍后,可以重新回头迭代
Three differences, and the list of analytical style
- Generator expressions are calculated on demand (or lazy evaluation, calculation delay) when it is required to calculate ---
- List analytic formula is immediately returned value
Contrast Four, and the list of analytical style
1, calculated
- Generator expression delay calculation, is calculated immediately analytical listing
2, memory footprint
- It returns a single value from itself, generator expressions province memory, analytical formula returns a list of the new list
- No data generator, takes very little memory, but when in use, although one return data, but the memory occupied together almost
- List-structure analytical new list, returns immediately, at the same time requires significant memory; and Builder is dispersed in time and space occupied by calculating
3, computing speed
- From time to read a single calculation, generator expressions consuming very short, time-consuming analytical expression list
- However, the generator itself does not return any value, only returns a generator object
- List analytic expression constructs and returns a new list
V. Summary
- python2 introduction of list-style
- python2.4 introduced generator expression
- python3 set of applications, Dictionary analytical formula, and migrate to 2.7
1, in general, should be more analytically style, because analytical formula short, high efficiency (interpreter will do optimization)
2, if an analytical formula is very complicated, difficult to read, to consider disassembled into a for loop
Generating and iterators are different objects, but they are iterables