zoukankan      html  css  js  c++  java
  • python基本用法笔记合集

    PYTHONPATH

    PYTHONPATH是python moudle的搜索路径.即import xxx会从$PYTHONPATH寻找xxx.

    中文编码问题

    coding=utf-8

    查看导入的包的路径

    import a_module
    print(a_module.file)

    map(function, iterable, ...)

    参数
    function -- 函数
    iterable -- 一个或多个序列

    返回值
    Python 2.x 返回列表。
    Python 3.x 返回迭代器。

    >>>def square(x) :            # 计算平方数
    ...     return x ** 2
    ... 
    >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
    [1, 4, 9, 16, 25]
    >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
    [1, 4, 9, 16, 25]
     
    # 提供了两个列表,对相同位置的列表数据进行相加
    >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    [3, 7, 11, 15, 19]
    

    What is :: (double colon) in Python when subscripting sequences?

    https://stackoverflow.com/questions/3453085/what-is-double-colon-in-python-when-subscripting-sequences

    It returns every item on a position that is a multiple of 3. Since 3*0=0, it returns also the item on position 0. For instance: range(10)[::3] outputs [0, 3, 6, 9]

    每隔xxx个元素做切片

    transpose

    比如img是h*w*c维(h是第0维,w是第1维,c是第2维)的矩阵. 在经过transpose((2,0,1))后变为c*h*w的矩阵

    enumerate

    >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
    

    range(start, stop[, step])

    • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
    • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
    • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
    
    >>>range(10)        # 从 0 开始到 10
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1, 11)     # 从 1 开始到 11
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> range(0, 30, 5)  # 步长为 5
    [0, 5, 10, 15, 20, 25]
    >>> range(0, 10, 3)  # 步长为 3
    [0, 3, 6, 9]
    >>> range(0, -10, -1) # 负数
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> range(0)
    []
    >>> range(1, 0)
    []
    
    

    super(type[, object-or-type])

    详细地看:http://www.runoob.com/python/python-func-super.html

    简单地说就是为了安全地继承.记住怎么用的就行了.没必要深究.

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class A(object):   # Python2.x 记得继承 object
        def add(self, x):
             y = x+1
             print(y)
    class B(A):
        def add(self, x):
            super(B, self).add(x)
    b = B()
    b.add(2)  # 3
    

    print

    print('name: "%s"' % props['name'],fp) //把字符串写入文件fp

    random用法

    random.choice(sequence)

    https://pynative.com/python-random-choice/

    • random.choice 选中一个
    • random.sample(sequence,k=) 选中多个
    import random
    path = "/home/train/disk/data/yulan_park_expand"
    random.choices([x for x in os.listdir(path)
                   if os.path.isfile(os.path.join(path, x))],k=2000)
    

    shell 工具

    from shutil import copyfile
    
    copyfile(src, dst)
    

    参数解析

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('num1',type=int,help="img numbers to random")
    parser.add_argument('num2',type=int,help="img numbers to random")
    args = parser.parse_args()
    
    

    命令行参数不带'-'开头的,就是类似于占位符,按顺序赋值. 比如python xxx.py 1 2则args.num1=1,args.num2=2. python xxx.py 2 1则args.num1=2,args.num2=1.

    def arg_parse():
        parser = argparse.ArgumentParser()
        parser.add_argument('-d','--dir',type=str,default='./data',required='True',help='dir store images/label file')
        parser.add_argument('-o','--output',type=str,default='./outdata.tfrecord',required='True',help='output tfrecord file name')
    
        args = parser.parse_args()
        
        return args
    
    • -d --dir说明命令行上传参用法.
    • type说明参数数据类型
    • default说明默认值
    • required说明是否为必选参数
    • help是参数的说明

    类名直接调用

    之前在pytorch和keras中经常发现一个类model被直接调用,发现很有意思。于是就去看了看pytorch中nn.Module的源码,发现是定义了__call__(self)函数再去调用forward()函数。举个例子如下:

    import math
    class Pow(object):
    	def __init__(self,n=2):
    		self.n=n
    		super(Pow,self).__init__()
    	def forward(self,x):
    		return math.pow(x,self.n)
    	def __call__(self,x):
    		return self.forward(x)
    l=Pow(2)
    y=l(10)
    print(y)  #输出结果是100
    l=Pow(3)
    y=l(10)
    print(y)  #输出结果是1000
    

    os模块

    os.walk

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import os
    for root, dirs, files in os.walk(".", topdown=False):
        for name in files:
            print(os.path.join(root, name))
        for name in dirs:
            print(os.path.join(root, name))
    

    #!/usr/bin/env python与#!/usr/bin/python的区别

    脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它,就这么简单

    同时对2个list做相同的乱序操作

    import random
    
    a = ['a', 'b', 'c']
    b = [1, 2, 3]
    
    c = list(zip(a, b))
    
    random.shuffle(c)
    
    a, b = zip(*c)
    
    print a
    print b
    
    [OUTPUT]
    ['a', 'c', 'b']
    [1, 3, 2]
    

    yield用法

    yield在函数中的功能类似于return,不同的是yield每次返回结果之后函数并没有退出,而是每次遇到yield关键字后返回相应结果,并保留函数当前的运行状态,等待下一次的调用。如果一个函数需要多次循环执行一个动作,并且每次执行的结果都是需要的,这种场景很适合使用yield实现。
    包含yield的函数成为一个生成器,生成器同时也是一个迭代器,支持通过next获取下一个值。
    yield基本使用:

    def func():
        for i in range(0,3):
            yield i
     
    f = func()
    print(next(f))
    
    for i in f:
        print(i)
    

    输出

    0
    1
    2
    
  • 相关阅读:
    erwin逆向工程,logical模型列名修改为中文
    [Leetcode] Two pointer-- 76. Minimum Window Substring
    [Leetcode] Binary search tree -- 173. Binary Search Tree Iterator
    [Leetcode] 684. Redundant Connection
    [Leetcode] Binary tree--653. Two Sum IV
    [Leetcode] Binary tree -- 617. Merge Two Binary Trees
    [Leetcode] Binary tree-- 563. Binary Tree Tilt
    [Leetcode] Binary tree-- 572. Subtree of Another Tree
    [Leetcode] Binary tree-- 437. Path Sum III
    [Leetcode] Binary tree-- 113. Path Sum II
  • 原文地址:https://www.cnblogs.com/sdu20112013/p/11216584.html
Copyright © 2011-2022 走看看