• python逼格提升


    1.合并可以匹配的条件

    1 s1 = 7
    2 if s1 > 5 and s1 < 10:
    3     print(s1)
    4 
    5 
    6 s1 = 7
    7 if 5 < s1 < 10:
    8     print(s1)

    2.if条件避免与布尔值比较

     1 l1 = []
     2 if l1 != []:
     3     print('l1 is not empty')
     4 else:
     5     print('l1 is empty')
     6 
     7     
     8 l1 = []
     9 if l1:
    10     print('l1 is not empty')
    11 else:
    12     print('l1 is empty')

    此时等价于if True,属于False的值:None、False、数字0、空列表元组字典集合,但是有的时候数字0我们是有用的,所以我们用is来比较

     1 s1 = 0
     2 if s1:
     3     print('s1 is not empty')
     4 else:
     5     print('s1 is empty')
     6 
     7     
     8 s2 = 0
     9 if s2 is not None:
    10     print('s2 is not empty')
    11 else:
    12     print('s2 is empty')

    so,我们可以看出is与==的意义是不同的,事情的真相是is比较的是内存地址,None在python是单例的,==比较的是值

     1 l1 = [0, 1, 2]
     2 l2 = [0, 1, 2]
     3 if l1 is l2:
     4     print('l1 is l2')
     5 else:
     6     print('l1 is not l2')
     7 
     8 if l1 == l2:
     9     print('l1 == l2')
    10 else:
    11     print('l1 != l2')

    3.简单的if else用三元运算代替

    1 if 1 == 2:
    2     s1 = '北方姆Q'
    3 else:
    4     s1 = 'bfmq'
    5 
    6 
    7 s1 = '北方姆Q' if 1 == 2 else 'bfmq'

    4.enumerate迭代器,可以循环的对象可以使用,返回两个值,第一个是位置,第二个是对应元素

    1 l1 = ['dfmq', 'xfmq', 'nfmq', 'bfmq']
    2 for index, value in enumerate(l1):
    3     print('%d %s' % (index, value))

    5.for+else表示当循环完for内所有后才会执行else下的程序,中途break则不会

    1 l1 = [11, 22, 33, 44]
    2 
    3 for s1 in l1:
    4     if s1 <= 100:
    5         break
    6 else:
    7     print('喵喵喵喵!')

    6.少定义布尔返回值变量

     1 def low1(a, b, c):
     2     flag = False
     3     if a == b == c:
     4         flag = True
     5     return flag
     6 
     7 ret = low1(6, 6, 6)
     8 
     9 
    10 def low2(a, b, c):
    11     if a == b == c:  
    12         return True
    13     else:
    14         return False
    15 
    16 ret = low2(6, 6, 6)
    17 
    18 
    19 def f1(a, b, c):
    20     return a == b == c
    21 
    22 ret = f1(6, 6, 5)

    7.被调用事不要抛出自定义异常

    1 def get_json_url(url):
    2     try:
    3         url = json.load(url)
    4         return url
    5 
    6     except Exception as e:
    7         print('something wrong!')
    8         return None

    这样第三方只会获得一个something wrong!信息,无法确定哪里出了错误,so
    def get_json_url(url):
      return json.load(url)
    这样异常会返回给调用者

    8.多用EAFP,少用LBYL

     1 def get(user):
     2     if user is None:
     3         print('no user!')
     4     print(user.info)
     5 LBYL在进行程序前需要考虑前提条件是否成立,因此穿插了很多条件检查
     6 
     7 
     8 def get(user):
     9     try:
    10         print(user.info)
    11 
    12     except NameError:
    13         print('no user!')

    9.连等号赋同值

    1 a = 10
    2 b = 10
    3 c = 10
    4 
    5 
    6 a = b = c = 10
    7 此时a=666,但是b跟c是不会变的哦~

    10.python支持直接调换值哦

     1 10.python支持直接调换值哦
     2 a = 10
     3 b = 100
     4 temp = a
     5 a = b
     6 b = temp
     7 
     8 
     9 a = 10
    10 b = 100
    11 a, b = b, a

    11.多次调用对象方法时,可以用链式调用方法,避免中间产生过多变量及内存

    1 s1 = '  north is good!'
    2 s2 = s1.strip()
    3 s3 = s2.upper()
    4 s4 = s3.replace('!', '?')
    5 
    6 
    7 s2 = s1.strip().upper().replace('!', '?')
    8 当然过多了连续调用可能会影响到可读性,so,简短的调用可以写在一起,出现一个比较大变化时另起一行是比较好的

    12.使用isinstance对不同类型参数进行对应操作

     1 def get_size(some_object):
     2     if isinstance(some_object, (list, dict, str, tuple, set)):
     3         return len(some_object)
     4     elif isinstance(some_object, (bool, type(None))):
     5         return 1
     6     elif isinstance(some_object, (int, float)):
     7         return int(some_object)
     8 
     9 
    10 print(get_size('bfmq'))
    11 print(get_size([1, 2, 3, 4, 5]))
    12 print(get_size(10.0))
    13 print(get_size([]))

     13.使用product精简多层嵌套循环

     1 from itertools import product
     2 
     3 x_list = ['a', 'b', 'c']
     4 y_list = ['d', 'e', 'f']
     5 z_list = [1, 2, 3]
     6 
     7 for x in x_list:
     8     for y in y_list:
     9         for z in z_list:
    10             print(f"{x}:{y}:{z}")
    11 
    12 
    13 for x, y, z in product(x_list,y_list, z_list):
    14     print(f"{x}:{y}:{z}")

    14.使用any/all进行判断

     1 i_list = [x for x in range(10)]
     2 
     3 for i in i_list:
     4     if i > 5:
     5         print(True)
     6         break
     7 
     8 
     9 if any(i > 5 for i in i_list):
    10     print(True)
  • 相关阅读:
    python 汇总
    python 异常处理、文件常用操作
    python类中super()和__init__()的区别
    百度搜索结果爬虫
    BS4爬虫实例应用-CISP
    Java类WebServer及中间件拿webshell方法总结
    建模分析之机器学习算法(附python&R代码)
    [原创]代理转发工具汇总分析
    代码审计之文件操作
    PHP自带防SQL攻击函数区别
  • 原文地址:https://www.cnblogs.com/bfmq/p/6813946.html
Copyright © 2020-2023  润新知