• Pythonic


      写这篇随笔,主要是因为自己是从c/c++开始的,写python的时候,难免有浓重的c++味道,为了让自己的python更加额pythonic,特写下这边随笔,记录自己遇到的pythonic的写法

    让自己的代码更加的pythonic。

    1、for循环

       实现对一个序列里的每个元素执行一个操作的 C 语言实现:

    1 for (i=0; i < mylist_length; i++) {
    2 
    3    do_something(mylist[i]);
    4 
    5 }

       等价于python中这样的语法:

    i = 0
    
    while i < mylist_length:
    
       do_something(mylist[i])
    
       i += 1

      这段代码能够完成工作,但并不 Pythonic。典型的 Python 惯用法是用内置的 range() 函数生成所有的序列下标:

    for i in range(mylist_length):
    
       do_something(mylist[i])

     语言推荐的实现方式,真正 Pythonic 实现:

    for element in mylist:
    
       do_something(element)

    2、置换

       通用的语法:

    1 temp = a
    2 a = b
    3 b = temp

      pythonic语法:

    a,b = b,a

    3、多返回值问题

     c语言的写法通常使用指针或者引用:

    1 void foo(int* a, float* b) {
    2 
    3     *a = 3;
    4 
    5     *b = 5.5;
    6 
    7 }

    pythonic用法:

    def foo():
        return 3, 5.5
    
    alpha, beta = foo()

    4、真假值问题

     判断是否都不为null

    name = 'Tim'
    langs = ['AS3', 'Lua', 'C']
    info = {'name': 'Tim', 'sex': 'Male', 'age':23 }   

     通用的语法:

    if name != '' and len(langs) > 0 and info != {}:
         print('All True!') #All True!

    pythonic语法:

    if name and langs and info:
         print('All True!')  #All True!

    附上真假值表:

    True False
    任意非空字符串 空的字符串 ''
    任意非0数字 数字0
    任意非空容器 空的容器 [] () {} set()
    其他任意非False None

    5、链式

    a = 3
    b = 1 

    通用:

    b >= 1 and b <= a and a < 10 #True

    pythonic语法:

    1 <= b <= a < 10  #True

    6、字符串翻转

    通用:

    1 def reverse_str( s ):
    2      t = ''
    3      for x in xrange(len(s)-1,-1,-1):
    4          t += s[x]
    5      return t

    pythonic:

    def reverse_str( s ):
         return s[::-1]

    如果用于检测回文,就是一句话input == input[::-1],多么的优雅!

    7、string.join()

    strList = ["Python", "is", "good"]  

    通用:

    res = ''
    for s in strList:
         res += s + ' '

    pythonic:

    res =  ' '.join(strList)

    8、列表的求和、求最大值、最小值、乘积

    numList = [1,2,3,4,5] 

    通用:

     sum = 0
     maxNum = -float('inf')
     minNum = float('inf')
     prod = 1
     for num in numList:
         if num > maxNum:
             maxNum = num
         if num < minNum:
             minNum = num
         sum += num
         prod *= num

    pythonic:

    sum = sum(numList)  #sum = 15
    maxNum = max(numList) #maxNum = 5
    minNum = min(numList) #minNum = 1
    from operator import mul
    prod = reduce(mul, numList) #prod = 120

    9、列表推导式

    通用:

    l = []
     for x in range(10):
         if x % 3 == 0:
             l.append(x*x)

    pythonic:

    l = [x*x for x in range(10) if x % 3 == 0]

    10、字典默认值

    dic = {'name':'Tim', 'age':23}

    通用:

    if 'workage' in dic:
         dic['workage'] += 1
    else:
         dic['workage'] = 1
    #dic = {'age': 23, 'workage': 1, 'name': 'Tim'}

    pythonic:

    dic['workage'] = dic.get('workage',0) + 1
    #dic = {'age': 23, 'workage': 1, 'name': 'Tim'}

    11、for循环中断情况

    通用:

    find = False
     for x in xrange(1,5):
         if x == 5:
             find = True
             print 'find 5'
             break
     if not find:
         print 'can not find 5!'
     #can not find 5!

    pythonic:

    for x in xrange(1,5):
         if x == 5:
             print 'find 5'
             break
     else:
         print 'can not find 5!'
     #can not find 5!  

    for...else...的else部分用来处理没有从for循环中断的情况。有了它,我们不用设置状态变量来检查是否for循环有break出来,简单方便。

    12、键与值

    通用:

    for i in xrange(len(array)):
         print i, array[i]

    pythonic:

    for i, e in enumerate(array,0):
         print i, e

    13、dict

    keys = ['Name', 'Sex', 'Age']
    values = ['Tim', 'Male', 23]

    通用:

    dic = {}
    for i,e in enumerate(keys):
         dic[e] = values[i]
    #{'Age': 23, 'Name': 'Tim', 'Sex': 'Male'}

    pythonic:

    dic = dict(zip(keys, values))
    #{'Age': 23, 'Name': 'Tim', 'Sex': 'Male'}

    14、数组合并

    L=[ [1,2,3],[4,5,6],[7,8,9]] 这样的列表,如何把合并成[1,2,3,4,5,6,7,8,9]

    通用:

    ret = []
    for x in L:
        ret += x
    print(x)

    使用标准库中的itertools模块:

    from itertools import chain
    lst = list(chain(*L))

    pythonic:

    myList = [x for j in L for x in j]
  • 相关阅读:
    第三章 p62 或运算
    p57 字符串的长度
    p53 ASCII码
    整数类型,如同时钟
    重要:原码、反码、补码...
    p42 实验溢出(上溢)
    P40 字节单位:KMGT
    p38 二、八、十六进制的对应关系
    p13 数组元素的地址
    p11 内存中的数据和地址
  • 原文地址:https://www.cnblogs.com/kefeiGame/p/8145084.html
Copyright © 2020-2023  润新知