美文网首页
python编程常用技巧

python编程常用技巧

作者: zealscott | 来源:发表于2018-05-21 10:59 被阅读0次

    python是一门很灵活的解释性语言,本人在阅读别人优秀代码时会遇到一些有意思的编程技巧,故写下来方便回顾。
    本文将在这里长期更新

    总结python知识点:python interview

    巩固Numpy知识:101 NumPy Exercises for Data Analysis

    python内置函数

    1. List Comprehensions

      一种简易的循环+创建list的方式,很常用。

    2. zip

      可快速的将两个向量中的对应元素合并成一个tuple。

    3. defaultdict

    4. (n,)与(n,1)区别:(n,1)可方便的进行broadcast。

    5. python使用分号

    6. operator.itemgetter

      定义一个获取对象哪些维的函数

    7. 字典的使用

      • item()

        • 返回一个列表对象
      • iteritems()

        • 返回一个迭代器
      • 如何将一个字典的value按照从小到大排列?

        • classCount = defaultdict(lambda: 0)
              for vote in classList:
                  classCount[vote] += 1
              sortedClassCount = sorted(classCount.iteritems(),\
                         key=operator.itemgetter(1), reverse=True)
          
    8. 函数属性实现全局变量

      • def fuc1():
            #通过一个 ".",使用了fuc2的变量
            b = fuc2.a 
            print b
        
        def fuc2():
            #这里需要注意的是,在fuc2函数内部使用a,同样要进行域确定,即
            #fuc2.a,才能访问
            fuc2.a = 0
            fuc1()
        
        fuc2()  #打印的结果是 0
        #访问fuc2的变量
        print fuc2.a #打印的结果还是 0
        
        #当在外面进行值变化时,fuc2的变量改变了,从而实现了全局变量的效果
        fuc2.a = 2
        fuc1() #全局变量的实现,现在输出的结果是 2
        
    9. Python3中dict实现按key返回:

    10. @staticmethod 和@classmethod

    @classmethod 为类方法,只在类中运行不在实例中运行,可以通过实例调用或者类调用,第一个参数为类名。

    @staticmethod 为静态方法,只能用类名调用。

    Numpy函数使用

    1. np.argmax:找到数组的指定axis的最大值下标

    2. np.random.randn:生成标准正态分布的随机数。

    3. np.linalg.norm :计算向量的二范数或者无穷范数等。

    4. np.nan_to_num :将NAN代替为0,无穷数代替为有限数。

    5. np.linspace、np.arange():创建等差数列

      np.logspace:创建等比数列

    matplotlib使用

    1. 绘制标注

      • 所有的变量可以参考

      • 参考示例

      • import numpy as np
        import matplotlib.pyplot as plt
        
        fig = plt.figure()
        ax = fig.add_subplot(111, polar=True)
        r = np.arange(0,1,0.001)
        theta = 2*2*np.pi*r
        line, = ax.plot(theta, r, color='#ee8d18', lw=3)
        
        ind = 800
        thisr, thistheta = r[ind], theta[ind]
        ax.plot([thistheta], [thisr], 'o')
        ax.annotate('a polar annotation',
                    xy=(thistheta, thisr),  # theta, radius
                    xytext=(0.05, 0.05),    # fraction, fraction
                    textcoords='figure fraction',
                    arrowprops=dict(facecolor='black', shrink=0.05),
                    horizontalalignment='left',
                    verticalalignment='bottom',
                    )
        plt.show()
        
    2. plt.xticks(my_x_ticks)

      人为设置坐标轴

      x.set_xlim(0,100)

      人为设置坐标轴范围

    3. ax.set_xscale('log', basex=2)

      指定坐标轴方式,可为任意阶指数,参考

    相关文章

      网友评论

          本文标题:python编程常用技巧

          本文链接:https://www.haomeiwen.com/subject/zklfjftx.html