python-day14 (formal learning)

A triplet of expressions

Return Values ​​When the condition else if condition is not satisfied when the conditions are satisfied

x = 10
y = 20

print(f"x if x > y else y: {x if x > y else y}")
x if x > y else y: 20

List comprehensions

[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
类似于
res=[]
for item1 in iterable1:
    if condition1:
        for item2 in iterable2:
            if condition2
                ...
                for itemN in iterableN:
                    if conditionN:
                        res.append(expression)
                        
print(F"[i for i in range(10)]: {[i for i in range(10)]}")

##[i for i in range(10)]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(F"[i**2 for i in range(10)]: {[i**2 for i in range(10)]}")

##[i**2 for i in range(10)]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

To be honest futile, only the loading force. . .

Dictionary of formula

print({i: i**2 for i in range(10)})
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

zip () method

keys = ['name', 'age', 'gender']
values = ['nick', 19, 'male']

res = zip(keys, values)
print(F"zip(keys,values): {zip(keys,values)}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")


##zip(keys,values): <zip object at 0x11074c088>
##info_dict: {'name': 'nick', 'age': 19, 'sex': 'male'}

Generated by decompressing a dictionary function

info_dict = {'name': 'nick', 'age': 19, 'gender': 'male'}
print(f"info_dict.keys(): {info_dict.keys()}")
print(f"info_dict.values(): {info_dict.values()}")

res = zip(info_dict.keys(), info_dict.values())
print(F"zip(keys,values): {zip(info_dict.keys(),info_dict.values())}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")


##info_dict.keys(): dict_keys(['name', 'age', 'gender'])
##info_dict.values(): dict_values(['nick', 19, 'male'])
##zip(keys,values): <zip object at 0x1105cefc8>
##info_dict: {'name': 'nick', 'age': 19, 'gender': 'male'}

This little use. . .

Builder

the yield keyword

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)
<generator object func at 0x10ddb6b48>

Generator is essentially an iterator, but also not just an iterator, but uses other than the iterator is really small, so we can proudly say: generator provides a very convenient way of self-defined iterator. And starting from the Python 2.5+, [PEP 342: Generator achieve synergies through enhanced program] achieved by adding more features to the generator, which means that the generator can also get more work done. In this section we will introduce later in the section.

def func():
    print('from func 1')
    yield 'a'
    print('from func 2')
    yield 'b'


g = func()
print(F"g.__iter__ == g: {g.__iter__() == g}")

res1 = g.__next__()
print(f"res1: {res1}")

res2 = next(g)
print(f"res2: {res2}")

# next(g)  # StopIteration
g.__iter__ == g: True
from func 1
res1: a
from func 2
res2: b
def func():
    print('from func 1')
    yield 'a'
    print('from func 2')
    yield 'b'


g = func()
for i in g:
    print(i)

print(f"list(func()): {list(func())}")
from func 1
a
from func 2
b
from func 1
from func 2
list(func()): ['a', 'b']

Builder there is no need to add a return

Iteration Iteration sets

If I need to access another generator in the generator's iterative process an iterative how to do? Written below so silly, very naive. And what your intention is to do this? ? ?

def sub_generator():
    yield 1
    yield 2
    for i in range(3):
        yield i


for i in sub_generator():
    print(i)
##  
1
2
0
1
2
##
def sub_generator():
    yield 1
    yield 2
    yield from range(3)


for i in sub_generator():
    print(i)
##
1
2
0
1
2
##

send(value)

The method of addition is next send another recovery generator. Python2.5 + in, yield statements into a yield expression, which means you can now have a yield value, and this value is to be called upon to restore execution method parameters send send method call generator.

def h():
    print('--start--')
    first = yield 5  # 等待接收 Fighting! 值
    print('1', first)
    second = yield 12  # 等待接收 hahaha! 值
    print('2', second)
    yield 13
    print('--end--')


g = h()
first = next(g)  # m 获取了yield 5 的参数值 5
# (yield 5)表达式被赋予了'Fighting!',  d 获取了yield 12 的参数值12
second = g.send('Fighting!')
third = g.send('hahaha!')  # (yield 12)表达式被赋予了'hahaha!'
print(f'--over--')
print(f"first:{first}, second:{second}, third:{third}")
--start--
1 Fighting!
2 hahaha!
--over--
first:5, second:12, third:13
  • Send incoming calls before non-None value, the generator must be in a suspended state, otherwise it will throw an exception. However, it does not start the generator can still use None as calling the send.
  • If you use the next recovery generator, the value of yield expression will be None.

close()

This method is used to close the generator. Call or send again to close next generation will raise StopIteration right.

def repeater():
    n = 0
    while True:
        n = (yield n)


r = repeater()
r.close()
print(next(r))  # StopIteration

throw()

Interrupt Generator is a very flexible technique can throw an exception through a GeneratorExit throw to terminate the Generator. Close () method does the same thing, in fact, inside it is called throw (GeneratorExit) of. We see the close of the source code:

def close(self):
    try:
        self.throw(GeneratorExit)
    except (GeneratorExit, StopIteration):
        pass 
    else:
        raise RuntimeError("generator ignored GeneratorExit") # Other exceptions are not caught

Custom range method

def my_range(start, stop, step=1):
    while start < stop:
        yield start
        start += 1


g = my_range(0, 3)
print(f"list(g): {list(g)}")

list(g):[0,1,2]

yield:

  1. To provide a custom iterator way
  2. yield can live pause function, and provide a current return value

yield和return:

  1. The same point: both are functions used internally, can return values, and return value does not limit the type and number of
  2. Different points: return can only return once it; yield may return multiple values

Generator expressions

  • The list of derived formula [] with () is the generator expression
  • Advantages: Provincial memory, once produced only one value in memory
t = (i for i in range(10))
print(t)
print(f"next(t): {next(t)}")
<generator object <genexpr> at 0x1101c4888>
next(t): 0

Anonymous function

Anonymous function, he has no name binding, ie, once recovered, either bracketed run.

lambda x, y: x+y
##<function __main__.<lambda>(x, y)>
res = (lambda x, y: x+y)(1, 2)
print(res)
##3

Inline function in combination with

1. If we want to remove the highest-paid people from the dictionary, we can use the max () method, but the max () the comparison is the default dictionary key.

  1. First iterables become iterator object
  2. res = next (iterator object), the parameters passed to the function key res as specified, and returns the value as determined according to the function
salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}

print(f"max(salary_dict): {max(salary_dict)}")


def func(k):
    return salary_dict[k]


print(f"max(salary_dict, key=func()): {max(salary_dict, key=func)}")
# 'nick', v1 = func('nick')
# 'jason', v2 = func('jason')
# 'tank', v3 = func('tank')
# 'sean', v4 = func('sean')


print(
    f"max(salary_dict, key=lambda name: salary_dict[name]): {max(salary_dict, key=lambda name: salary_dict[name])}")
max(salary_dict): tank
max(salary_dict, key=func()): jason
max(salary_dict, key=lambda name: salary_dict[name]): jason

2. If we want the dictionary in the above-mentioned people descending order according to salary, you can use the sorted () method.

sorted () works:

  1. First iterables become iterator object
  2. res = next (iterator object), res as the argument to the function specified by the first parameter, and returns the value as determined according to the function.
lis = [1, 3, 2, 5, 8, 6]
sorted(lis)
print(f"lis: {lis}")
print(f"sorted(lis,reverse=True): {sorted(lis,reverse=True)}")

##lis: [1, 3, 2, 5, 8, 6]
##sorted(lis,reverse=True): [8, 6, 5, 3, 2, 1]

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}

print(
    f"sorted(salary_dict, key=lambda name: salary_dict[name]): {sorted(salary_dict, key=lambda name: salary_dict[name])}")

##sorted(salary_dict, key=lambda name: salary_dict[name]): ['sean', 'nick', 'tank', 'jason']

3. If we want a list of names to do a deal, you can use the map () method.

map () works:

  1. First iterables become iterator object
  2. res = next (iterator object), res as the argument to a function specified by the first parameter, and then returns as one map () method of the function result value.
name_list = ['jason', 'tank', 'sean']

res = map(lambda name: f"{name} sb", name_list)
print(f"list(res): {list(res)}")

##list(res): ['jason sb', 'tank sb', 'sean sb']

4. If we want to filter contains the name of the name 'sb' in addition, we can use the filter () method.

filter () works:

  1. First iterables become iterator object
  2. res = next (iterator object), as a function of the res parameters specified by the first parameter passed, then the filter will determine the return value of the function is true, if true left.
name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']

filter_res = filter(lambda name: name.endswith('sb'), name_list)
print(f"list(filter_res): {list(filter_res)}")

##list(filter_res): ['jason sb', 'tank sb', 'sean sb']

Guess you like

Origin www.cnblogs.com/leaf-wind/p/11348848.html