Ternary expressions with the formula

Thirteen yuan expression

A triplet of expressions is a simplified code python for us to provide solutions to the following syntax:

res = 条件成立时要返回的值  if  条件  else  条件不成立时要返回的值

Specific case columns:

res = 1 if 1 > 2 else 2
print(res) #2

Modifications to the following requirements into a triplet of expressions:

A common format:

def func(x,y):
  	if x > y:
      return x
    else:
      return y
   
res = func(1,2)
print(res)#2

Three yuan expression format:

def func(x, y):
    res = x if x > y else y
    return res
res = func(5, 2)
print(res)  # 5

Two lists of Formula

List of Formula is a simplified solution python code that provides us used to quickly generate a list of

l = ['alex_dsb', 'egon', 'wxx_dsb', 'lxx_dsb']
# new_l = []
# for name in l:
#     if name.endswith('dsb'):
#         new_l.append(name)
# print(new_l) #['alex_dsb', 'wxx_dsb', 'lxx_dsb']

#列表生成式
new_l = [name for name in l if name.endswith('dsb')]
print(new_l) #['alex_dsb', 'wxx_dsb', 'lxx_dsb']

#把所有小写字母都变成大写
new_l = [name.upper() for name in l]
print(new_l) #['ALEX_DSB', 'EGON', 'WXX_DSB', 'LXX_DSB']

#去掉后缀_dsb
new_l = [name.strip('_dsb') for name in l]
print(new_l) #['alex', 'egon', 'wxx', 'lxx']

Three dictionaries of formula

List of Formula is a simplified solution python code that provides us used to quickly generate dictionary

#字典生成式
keys = ['name', 'age', 'gender']
dic = {key:None for key in keys}
print(dic) #{'name': None, 'age': None, 'gender': None}

#去掉 gender 关键字
items = [('name', 'egon'),('age', 18), ('gender','female')]
dic = {key:value for key, value in items if key != 'gender'}
print(dic) #{'name': 'egon', 'age': 18}

Four collection formula

#集合生成式
keys = ['name', 'age', 'gender']
set1 = {key for key in keys}
print(set1,type(set1))  #{'gender', 'name', 'age'} <class 'set'>

Note: no tuples formula (tuples immutable)

Generator five formula

Creating a generator object in two ways: one is the function call with the yield keyword, and the other is the generator expression.

Generator expression returns a generator object

#生成式生成器
g = (i for i in range(7) if i>3)
print(g) #<generator object <genexpr> at 0x10408fe08>
#此刻g 内部一个值也没有

print(next(g)) #4
print(next(g)) #5
print(next(g)) #6
print(next(g)) #抛出异常

If we want to read the contents of a large number of characters in the file, it should be based on the complete expression pattern generator

The reason: the equivalent of a function generator, a very small memory footprint

#统计文件内容长度
with open('a.txt', 'r', encoding='utf-8')as f:
    #方式一
    # res = 0
    # for line in f:
    #     res += len(line)
    # print(res)
    
    #方式二
    res = sum([len(line) for line in f]) #sum 底层就相当于 for 循环取值再依次相加
    print(res)
    #方式三:效率最高
    res = sum((len(line) for line in f)) #使用生成器对象,不会占用过多的内存空间
    print(res)
    #上述可以简写为如下形式:
    res = sum(len(line) for line in f)
    print(res)

Guess you like

Origin www.cnblogs.com/xy-han/p/12567196.html