A triplet of expressions
Surrounding ternary expressions, the main role is to long list, many lines of code into the concentrate line. The so-called concentration is the essence. Doing so can save a lot of space to run the code
A triplet of expressions only supports dual-branch structure
The next section of code is a more general code biantennary structure
fronts = [1,2,4,4,7]
backs = [1,3,4,1,3]
a = set(fronts + backs)
for i, j in zip(fronts, backs):
if i == j:
a -= {i}
if a == set():
return 0
else:
return min(a)
If the ternary expression, then this code will become very simple:
fronts = [1,2,4,4,7]
backs = [1,3,4,1,3]
return min(set(fronts+backs)-{i for i, j in zip(fronts, backs) if i == j} or [0])
Is not feeling his face a question mark?
But in fact, a triplet of expressions just makes you less code, and logic itself has not changed. And others understand your code will become very difficult, so it is not recommended to use
List comprehensions
List can be used to derive the formula very simple manner the list of elements or other objects traverse iterations and filtered quickly generate a list to meet specific needs, readable code is very strong, Python is a program development of the most widely used technique One. The internal implementation of Python list comprehensions done a lot of optimization, can ensure fast speed, also recommended the use of a technology.
List comprehensions logically equivalent to a loop, but more concise form
aList = [x*x for x in range(10)]
# 等价于:
aList = []
for x in range(10):
aList.append(x*x)
Dictionary of formula
Dictionary formula generally zip (zip Function - "tuple inside the package list) in conjunction
It is similar to a list comprehension, but also in order to simplify the generation of dictionary
new_dic = {k * 2: v ** 2 for k, v in dic.items()}
print(new_dic)
z = zip(['a', 'b', 'c', 'd'], [1, 2, 3, 4]) # 压缩方法,Python解释器的内置方法
for k,v in z:
print(k,v)
Builder
Builder is a custom iterator, is made out of their own iterator
yield
yield of the English word meaning production, whenever the yield keyword appears in the function, and then call the function, the function body will not continue to execute the code, but will return a value
def func():
print(1)
yield
print(2)
yield
g = func()
print(g)
The main role of yield is cut off, but f placed here can achieve a lot of features, the essence generator iterators, but also not just an iterator
Three characteristics of yield
- yield function can become generator (custom iterator objects, and having ___iter__ __next__ method)
- yield function can be stopped, and then the next next run again yield the following code
- Yield of n generators have n elements, n can next time, the next time n + 1 will be given
return characteristics
1. Return value
2. termination function
def func():
yield [1,1,23] # yield会使函数func()变成生成器对象,因此他就具有__iter__方法
# print(789) # yield会停止函数,当运行下一次next才会继续运行下面的代码
yield 101112 # 一个yield对应一个next
# print(131415)
g = func()
for i in g:
print(i)
We can also try to use their own generators to develop a range (10)
def range(x):
count = 0
while count < x:
yield count
count += 1
Before long with variable parameters also mention a complete range
def range(*args, step=1):
args = list(args)
if len(args) == 1:
count = 0
while count < args[0]:
yield count
count += step
elif len(args) == 2:
while args[0] < args[1]:
yield args[0]
args[0] += step
Generator expressions
# 把列表推导式的[]换成()
lt = [i for i in range(10000000)]
print(lt)
g = (i for i in range(10000000))
print(g)
print(g.__next__())
The difference between lists and tuples: list is a basket of eggs, a tuple is an old hen (to save space)
Anonymous function
Anonymous functions, by definition, function without a name
Lambda keyword need anonymous
# lambda 参数:<代码块>
f = lambda x: x+1
res = f(1)
print(res)
Anonymous functions generally not used alone,, and filter () / map () / sorted () / list sort () method associated with built
salary_dict = {
'nick': 3000,
'jason': 100000,
'tank': 5000,
'sean': 2000
}
salary_list = list(salary_dict.items())
print(salary_list) # [('nick', 3000), ('jason', 100000), ('tank', 5000), ('sean', 2000)]
Such a code, if the built-in methods for sorting, it can only be sorted by key
If a named function, it can be done for value values are sorted, but it would be more trouble
If you use an anonymous function, then it will simply many
def func(i): # i = ('sean', 2000), ('nick', 3000),('tank', 5000),('jason', 100000)
return i[1] # 2000,3000,5000,100000
salary_list.sort(key=lambda i: i[1]) # 内置方法是对原值排序
# 按照func的规则取出一堆元素2000,3000,5000,100000
# 然后按照取出的元素排序
print(salary_list)