The python based learning 1

Advanced Functions

1*args, **kwargs

* args dynamically receive all the positional parameters
** kwargs receiving dynamic keyword arguments

Dynamic receive parameters of time to pay attention: a dynamic parameter must screens appear after positional parameters

def chi(*food, a, b):
    print("我要吃", food, a, b)
chi("⼤⽶饭", "⼩⽶饭", a="⻩⽠", b="茄⼦")

Location parameters dynamically in python, but this situation can only * receiving position parameter received ⽆ method keyword parameters . Receives dynamic keyword parameter manipulation Use python **

def func(**kwargs):
    print(kwargs)
func(a=1, b=2, c=3)
func(a=1, b=2)
结果:
{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2}

The final order (*):

Location parameter> * args> The default value of the parameter> ** kwargs

These four parameters can be arbitrary use if you want to receive all parameters:

def	func(*args, **kwargs): 
    print(args, kwargs)
func("麻花藤","晕",wtf="胡辣汤")
结果:
('麻花藤', '晕') {'wtf': '胡辣汤'}

Closure 2

If ⼀ functions Perform complete. The function of the content of local variables and namespace all will be destroyed. In the closure. If the variable is destroyed. It will not be an internal function Perform normal so. Python regulations. If you access the variables in the outer function in internal function. so this variable will not die. will be resident in memory.

Use for closure is to make ⼀ variables can be permanent memory. After the screen for the program for Use After Use # ⾯ need to screen for individual cases from the content does not need to Perform comes in handy in a time-consuming operation of the network connection is provided

Benefits: 1. Safety 2. permanent memory and improve efficiency.

3 iterators

Destination time before we know iterables str, list, tuple, dict, set. They have followed the protocol can be iterative.

Principle: - iter-- object of this class is ⼀ a iterables.

Application: For example, when we use crawlers can use an iterator, I can feel like a for loop, plus the internal function can call functions inside and save the permanent memory.

Features iterator: 2. 3. 1. To inert mechanisms of memory can only move forward.

4 Generator

What is ⽣ generator. ⽣ generator essence iterators.

def func():
    print("111")
 	yield 222
gener = func() # 这个时候函数不会执⾏. ⽽是获取到⽣成器
ret = gener.__next__() # 这个时候函数才会执⾏. yield的作⽤和return⼀样. 也是返回数据
print(ret)
结果: 
111
222

⽣ generator can use the for loop to get the inner elements:

def func():
    print(111)
    yield 222
    print(333)
    yield 444
    print(555)
    yield 666
    #yield和return的效果是⼀样的. 有什么区别呢? yield是分段来执⾏⼀个函数. return直接停⽌执⾏函数.
gen = func()
print(gen)
#结果:<generator object func at 0x000002F3C4B7D888>
for i in gen:
print(i)
# 结果:
# 111
# 222
# 333
# 444
# 555
# 666

⽣ list comprehensions and generator expressions of difference:

  1. List comprehensions more consumption of memory. ⼀-time load. ⽣ generator to get accustomed expression hardly account for Use memory. Using when it is allocated and Using memory

  2. ⼀ sample value is not obtained. The resulting formula is derived listing ⼀ lists. ⽣ generator expression is obtained ⽣ ⼀ a generator.

lst = [i for i in range(1, 100) if i % 2 == 0]
print(lst)
#列表推导式
#⽣成器表达式和列表推导式的语法基本上是⼀样的. 只是把[]替换成()
  1. List down the formula [The results for the variable in iterable if screening]
  2. Dictionary down for variables in the formula {result iterables result if screening} => key: value
  3. The results set down for the variable in the formula {iterables if the screening results} => key

5 lambda

  1. Function parameters can have a plurality of spaced plurality Use commas. Parameters

  2. Anonymous function no matter how complex. ⼀ ⾏ can only write, and returns the data directly after the end of logic

  3. Normal function return value and ⼀ like, can be any data type

# 计算n的n次⽅
def func(n):
    return n**n
print(func(10))
#lambda函数
f = lambda n: n**n
print(f(10))

6 sorted

Ordering function: sorted (Iterable, key = None, reverse = False)

Iterable: iterables

key: collation (sorting function), each element in the sorted ⼀ inner iteration object will be passed to this function

The number of parameters. Sorted into ⾏ function of the result of the calculation

reverse: whether it is a flashback True:. flashback, False: positive sequence

lst = ["麻花藤", "冈本次郎", "中央情报局", "狐仙"]
# 计算字符串⻓度
def func(s):
    return len(s)
print(sorted(lst, key=func))

结果:['狐仙', '麻花藤', '冈本次郎', '中央情报局']

lst = [{"id":1, "name":'alex', "age":18},
 {"id":2, "name":'wusir', "age":16},
 {"id":3, "name":'taibai', "age":17}]
# 按照年龄对学⽣信息进⾏排序
print(sorted(lst, key=lambda e: e['age']))

结果:[{'id': 2, 'name': 'wusir', 'age': 16}, {'id': 3, 'name': 'taibai', 'age': 17}, {'id': 1, 'name': 'alex', 'age': 18}]

7 filter

Filter function filter (function. Iterable)

function:. Use the filter function to automatically transfer of the filter to the elements in iterable function and the function returns True or False to determine whether this data is retained.

Iterable: iterables

lst = [{"id":1, "name":'alex', "age":18},
 {"id":2, "name":'wusir', "age":16},
 {"id":3, "name":'taibai', "age":17}]
fl = filter(lambda e: e['age'] > 16, lst) # 筛选年龄⼤于16的数据
print(list(fl))

结果:[{'id': 1, 'name': 'alex', 'age': 18}, {'id': 3, 'name': 'taibai', 'age': 17}]

8 map

Mapping function: map (function, iterable) can perform while mapping iterables each element were taken ⼀ YES.

function

#计算列表中每个元素的平⽅ ,返回新列表
def func(e):
    return e*e
mp = map(func, [1, 2, 3, 4, 5])
print(mp)
print(list(mp))

# 改写成lambda
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5])))

9 recursion

#在python中递归的深度最⼤到998
def foo(n):
    print(n)
    n += 1
    foo(n)
foo(1)
#在函数中调⽤函数本⾝. 就是递归

Recursive to apply it: we can use the recursion to traverse a variety of tree, such as our folder system can be accessed using recursion to loop through all the files in the folder.

import os
def read(filepath, n):
    files = os.listdir(filepath)  # 获取到当前⽂件夹中的所有⽂件
    for fi in files:  # 遍历⽂件夹中的⽂件, 这⾥获取的只是本层⽂件名
        fi_d = os.path.join(filepath, fi)  # 加⼊⽂件夹 获取到⽂件夹+⽂件
    if os.path.isdir(fi_d):  # 如果该路径下的⽂件是⽂件夹
        print("\t" * n, fi)
        read( fi_d, n + 1)  # 继续进⾏相同的操作
    else:
        print("\t" * n, fi)  # 递归出⼝. 最终在这⾥隐含着return

# 递归遍历⽬录下所有⽂件
read('../1newpy/', 0)

Guess you like

Origin www.cnblogs.com/wkjava/p/12652939.html