• Python 学习


    
    
    s='abcdefgdehde'
    print(s.find('de'))
    print(s.find('de',5))
    print(s.rfind('de'))
    print(s.find('ded',10,100))不存在,输出-1
    print(s.count('d'))
    print(s.index('def'),10) #不存在,直接报错
    答案:
    3
    7
    10
    -1
    3
    Traceback (most recent call last):
      File "C:/Users/Administrator/Desktop/处理/t1.py", line 7, in <module>
        print(s.index('ded'),10)
    ValueError: substring not found
    
    
    split 和join的用法
    >>> s='中国   你好    朱群喜'
    >>> s.split()
    ['中国', '你好', '朱群喜']
    >>> len(s.split())
    3
    
    >>> Hello='-'.join(['中国', '你好', '朱群喜'])
    >>> Hello
    '中国-你好-朱群喜'
    
    
    lower,upper,capitalize,title,swapcase
    字符串转换为小写、大写、首字母大写、每个单词的首字母大写、大小写互换
    s='What is Your name?'
    print(s.lower())
    print(s.upper())
    print(s.capitalize())
    print(s.title())
    print(s.swapcase())
    答案:
    what is your name?
    WHAT IS YOUR NAME?
    What is your name?
    What Is Your Name?
    wHAT IS yOUR NAME?
    
    s='中国,中国'
    print(s.replace('中国','中华人民共和国'))
    print(s)#s的值没有改变
    答案:
    中华人民共和国,中华人民共和国
    中国,中国
    
    strip使用
    a='cbagrfagfafca'
    print(a.strip('abc'))
    答案:
    grfagfaf
    
    eval使用
    print(eval('3+4'))
    import math
    print(eval('help(math.sqrt)'))
    
    
    
    #通过python 添加环境变量
    import
    os mingw_path = 'C:Program Filesmingw-w64x86_64-6.3.0-posix-seh-rt_v5-rev1mingw64in' os.environ['PATH'] = mingw_path + ';' + os.environ['PATH']

    使用数组索引数组

    例:产生一个一组数组,使用数组来索引出需要的元素。让数组[3,3,1,8]取出x中的第3,3,1,8的四个元素组成一个数组view

    >>> x = np.arange(10,1,-1)
    >>> x
    array([10,  9,  8,  7,  6,  5,  4,  3,  2])
    >>> x[np.array([3, 3, 1, 8])]
    array([7, 7, 9, 2])

    当然,类似切片那样,Index也可以使用负数。但是索引值不能越界!

    >>> x[np.array([3,3,-3,8])]
    array([7, 7, 4, 2])

    数组纵向合并 

    c = np.vstack((a,b))

    数组横向合并

    d = np.hstack((a,b))

     查询某个范围的数据

    >>> cond = (arr_num >=5) & (arr_num <= 26)
    
    >>> arr_2 = np.extract(cond, arr_num)
    
    >>> arr_2
    
    array([ 5,  6,  8,  9, 10, 13, 14, 15, 16, 17, 18, 25, 23,  9, 14])

    获取csv的表头

    X = pd.read_csv(data_path_X)
    feature_name=X.columns
    >>> import math
    >>> math.sqrt(3**2+4**2)
    5.0
    
    十六进制:0x1f    16+15=31
    八进制:0o11       8+1=9
    二进制:0b11       2+1=3
    
    复数:
    >>> a=3+4j
    >>> a.real
    >>> a.imag
    >>> a.conjugate() 共轭复数
    
    字符串:
    >>> a='abc'+'124'
    'abc124'
    
    三双引号或三单引号注释(支持换行)
    """
    1234
    """
    '''
    asdf
    '''
    
    字符串格式化:
    >>> '''My name is %s, and my age is %d'''%('Zhu qunxi',25)
    'My name is Zhu qunxi, and my age is 25'
    
    转义字符:
    
      换行符     ''       双引号
    	  制表符      \       一个
    
      回车         ddd   3位八进制数对应的字符
    '  单引号       xhh   2位十六进制对应的字符
    
    Python运算符
    x/y 除法      x//y整除     x%y取模(ps:浮点数也可以)     x**y幂运算     x!=y不等于
    x or y    x and y   not x    
    x in y; x not in y  成员测试运算符
    x is y; x is not y  对象实体统一性测试(地址)
    |,^,&,<<,>>,~ 位运算符  (例如: 3<<1等于6)
    &,|,^ 集合交集,并集,对称差集
    
    >>> 3*'a'
    'aaa'
    
    >>> 3*[1,2,3]
    [1, 2, 3, 1, 2, 3, 1, 2, 3]
    
    strip, lstrip, rstrip用法
    >>> ('aaa,,,').rstrip(',')   
    'aaa'
    >>> ('aaa,,1,12323').rstrip('123')
    'aaa,,1,'

     
    >>> a=[1,2,3,4]
    >>> b=[2,3,4,5] 
    >>> c=a+b
    [1, 2, 3, 4, 2, 3, 4, 5]   #拼接,不同于numpy数组的加法
    
    >>> d=list(map(str,c))   #map为python内置函数,不需要导入任何模块
    ['1', '2', '3', '4', '2', '3', '4', '5']
    
    >>> d=list(map(math.sin,c))
    [0.8414709848078965,
     0.9092974268256817,
     0.1411200080598672,
     -0.7568024953079282,
     0.9092974268256817,
     0.1411200080598672,
     -0.7568024953079282,
     -0.9589242746631385]
    
    python常用内置函数
    abs(x):绝对值, bin(x):将数字x转化为二进制串,chr(x):返回ASCII编码为x的字符
    cmp(x,y):x<y返回负数,x>y返回正数,,x==y返回0,Python 3不在支持
    dir(x):返回x的成员列表
    
    可以把list,tuple,dict和string相互转化。
    #################################################
    字符串转换成列表
    >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
    >>>type(a)
    <type 'str'>
    >>> b = eval(a)
    >>> print b
    [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
    >>> type(b)
    <type 'list'>
    #################################################
    字符串转换成字典
    >>> a = "{1: 'a', 2: 'b'}"
    >>> type(a)
    <type 'str'>
    >>> b = eval(a)
    >>> print b
    {1: 'a', 2: 'b'}
    >>> type(b)
    <type 'dict'>
    #################################################
    字符串转换成元组
    >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
    >>> type(a)
    <type 'str'>
    >>> b = eval(a)
    >>> print b
    ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
    >>> type(b)
    <type 'tuple'>
    def is_odd(x):
        return x % 2 == 1
    利用filter()过滤掉偶数,返回由符合条件元素组成的新list:
    filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
    
    
    利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    import math
    def is_sqr(x):
        return math.sqrt(x) % 1 == 0
    print filter(is_sqr, range(1, 101))
    
    float(x):将数字或字符串x转换为浮点数并返回
    >>> float('123.354')
    123.354
    >>> float(3)
    3.0
    
    >>> ('  asdf,asdf,adsf ').strip().split(',') 
    ['asdf', 'asdf', 'adsf']
    
    
    hex(x):将数字转换为十六进制串
    id(obj):返回对象obj的标识(地址)
    input([提示内容字符串])
    int(x):返回整数部分
    len(obj): 返回对象obj包含的元素个数,适合于元组,集合,字典,字符串,列表
    list([x]),set([x]),tuple([x]),dict([x]):转换成列表。。。
    map(函数,序列):映射,返回列表 (python 3 以上要加list)
    oct(x):把数字转化成八进制
    
    open/文件操作
    f=open('/tmp/hello','w')
    #open(路径+文件名,读写模式)
    #读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
    rb     以二进制读模式打开
    wb     以二进制写模式打开 (参见 w )
    r 只能读 
    r+ 可读可写 不会创建不存在的文件 从顶部开始写 会覆盖之前此位置的内容 
    w+ 可读可写 如果文件存在 则覆盖整个文件不存在则创建 
    w 只能写 覆盖整个文件 不存在则创建 
    a 只能写 从文件底部添加内容 不存在则创建 
    a+ 可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建 注意:
    1、使用'W',文件若存在,首先要清空,然后(重新)创建, f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串) file.readline() 返回一行 file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行 f.write("hello ") #如果要写入字符串以外的数据,先将他转换为字符串. 例子,读取csv文件,转换成xlsx格式输出:
    mainpath='E:/linwei/神经/Ge_csv/'
    filename = mainpath + 'labels.csv'
    filename_out='Yes.xlsx'
    f = open(filename)
    f_out = open(filename_out, "w")
    for line in f.readlines():
    data=(line.replace(',',' ')).strip()#把csv的逗号',’分隔符换成' '制表符
    f_out.write(data+" ")
    f_out.close()

    def f(x, y):
      return x + y
    调用 reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:
    先计算头两个元素:f(1, 3),结果为4;
    再把结果和第3个元素计算:f(4, 5),结果为9;
    再把结果和第4个元素计算:f(9, 7),结果为16;
    再把结果和第5个元素计算:f(16, 9),结果为25;
    由于没有更多的元素了,计算结束,返回结果25。

    reversed(列表或元组): 返回逆序后的迭代对象
    str(obj): 把对象obj转换为字符串
    round(x):对x四舍五入,返回的是整型
    
    类似C语言中对于结构体排序
    class Student:
        def __init__(self, name, grade, age):
            self.name = name
            self.grade = grade
            self.age = age
      
    def __repr__(self):#必须加上__repr__,否则就返回的是地址
        return repr((self.name, self.grade, self.age)
    student_objects = [Student('john', 'A', 15),Student('john', 'A', 10),Student('john', 'C', 10), Student('john', 'B', 10),Student('jane', 'B', 12),Student('dave', 'B', 10)] student_objects=sorted(student_objects, key=lambda x: (x.age,x.grade))#先按年龄,再按年级 print(student_objects)
    答案:[('john', 'A', 10), ('john', 'B', 10), ('dave', 'B', 10), ('john', 'C', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    from operator import itemgetter, attrgetter#用operator 函数来加快速度

    student_objects=sorted(student_objects, key=attrgetter('age', 'grade'))
    print(student_objects)
    student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
    student_objects=sorted(student_tuples, key=itemgetter(1,2))
    print(student_objects)
    答案:

     [('john', 'A', 10), ('john', 'B', 10), ('dave', 'B', 10), ('john', 'C', 10), ('jane', 'B', 12), ('john', 'A', 15)]
     [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

    
    
    #先看一下Boolean value 的排序:
    print(sorted([True,False]))#===>结果[False,True]

    list1=[7, -8, 5, 4, 0, -2, -5]
    #1.正数在前负数在后 2.整数从小到大 3.负数从大到小
    list1=sorted(list1,key=lambda x:(x<0,abs(x))) #负数满足x<0,返回True,所以负数排在后面;然后再按绝对值从小到大

      sorted(iterable, key=None, reverse=False)


    zip用法:
    x = [1, 2, 3]
    y = [4, 5, 6]
    z = [7, 8, 9]
    for i,j,k in zip(x,y,z):
    print(i,j,k)
    xyz = zip(x, y, z)
    print(list(xyz))
    输出:

     1 4 7
     2 5 8
     3 6 9
     [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

    __str__和__repr__
    如果要把一个类的实例变成 str,就需要实现特殊方法__str__():
    
    class Person(object):
        def __init__(self, name, gender):
            self.name = name
            self.gender = gender
        def __str__(self):
            return '(Person: %s, %s)' % (self.name, self.gender)
    现在,在交互式命令行下用 print 试试:
    
    >>> p = Person('Bob', 'male')
    >>> print p
    (Person: Bob, male)
    但是,如果直接敲变量 p:
    
    >>> p
    <main.Person object at 0x10c941890>
    似乎__str__() 不会被调用。
    
    因为 Python 定义了__str__()和__repr__()两种方法,__str__()用于显示给用户,而__repr__()用于显示给开发人员。
    
    有一个偷懒的定义__repr__的方法:
    
    class Person(object):
        def __init__(self, name, gender):
            self.name = name
            self.gender = gender
        def __str__(self):
            return '(Person: %s, %s)' % (self.name, self.gender)
        __repr__ = __str__


    内置函数max,min,sum的用法
    import random
    a=[random.randint(1,10) for i in range(10)]
    print(max(a),min(a),sum(a))
    sum(a)/len(a) #均值,Python 2.7 sum(a)*1.0/len(a)
    for i in range(10):
    print(i,end=' ') #输出不换行
    答案:0 1 2 3 4 5 6 7 8 9
    写入到指定文件
    f=open(name,'a+')
    print('hello!',file=f)
    f.close()

    模块导入与使用
    import 模块名 [as 别名]
    from 模块名 import 对象名 [as 别名] #好处:减少查询次数,提高访问速度,减少代码量,不需要使用模块名作为前缀
    from math import sin as f
    f(3)
    输出:0.14112

      

    python中if __name__ == '__main__': 的解析
    
    当你打开一个.py文件时,经常会在代码的最下面看到if __name__ == '__main__':,现在就来介 绍一下它的作用.
    模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,
    不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, __name__ 的值将是一个特别缺省"__main__"/////////////////////////////////////////////////////////////////////////////////////////////////// 在cmd 中直接运行.py文件,则__name__的值是'__main__'; 而在import 一个.py文件后,__name__的值就不是'__main__'了; 从而用if __name__ == '__main__'判断是否是在直接运行该.py文件 如: #Test.py class Test: def __init(self):pass def f(self):print 'Hello, World!' if __name__ == '__main__': Test().f() #End 你在cmd中输入: C:>python Test.py Hello, World! 说明:"__name__ == '__main__'"是成立的 你再在cmd中输入: C:>python >>>import Test >>>Test.__name__ #Test模块的__name__ 'Test' >>>__name__ #当前程序的__name__ '__main__' 无论怎样,Test.py中的"__name__ == '__main__'"都不会成立的! 所以,下一行代码永远不会运行到! //////////////////////////////////
    >>> list('helllo, world!')
    ['h', 'e', 'l', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
    
    import  time
    time.time()   返回当前时间
    
    列表的内置函数功能,ps:对原来的列表进行操作,不同与sorted!
    import random
    a=list(range(13))
    random.shuffle(a)
    print(a)
    a.sort()
    print(a)
    a.sort(reverse=True)
    print(a)
    a.sort(key=lambda x:len(str(x)))
    print(a)
    
    答案:
    [4, 0, 11, 8, 6, 9, 1, 2, 3, 10, 7, 5, 12]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 12, 11, 10]
    
    
    默认对字典的""进行计算(max,min,sum)
    a={'b':1,'a':2}
    print(max(a))
    print(max(a.values()))
    答案:
    b
    2
    
    enumerate枚举元素的下标和元素的值
    import numpy as np
    for i,j in enumerate(range(1,10,2)):
        print(i,j)
    答案:
    0 1
    1 3
    2 5
    3 7
    4 9
    
    列表推导式
    a=[' asdf ','asdg ',' gfs']
    b=[w.strip() for w in a]   #等价于b=list(map(str.strip,a))
    print(b)    
    答案:
    ['asdf', 'asdg', 'gfs']
    
    
    vec=[[1,2,3],[3,4,5],[6,7,8]]
    print(vec)
    ans=[w for i in vec for w in i]
    print(ans)
    答案:
    [[1, 2, 3], [3, 4, 5], [6, 7, 8]]
    [1, 2, 3, 3, 4, 5, 6, 7, 8]
    
    过滤不符合条件的元素
    import os
    # 返回当前的python文件
    name=[w for w in os.listdir() if 'py' in w]
    print(name)
    答案:
    ['deal_sort.py', 'deal_zip.py', 'ex1.py', 'read_csv or xlsx.py', 'read_file.py']

    上面等价于:
    import os
    # 返回当前的python文件
    # name=[w for w in os.listdir() if 'py' in w]
    def f(x):
    return 'py' in x
    name=list(filter(f,os.listdir('.')))
    print(name)

    [[x,y] for x in range(3) for y in range(3)]
    答案:
    [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

    ////////////////////////////////////////////////
    字典操作
    key=[chr(i) for i in range(97,100)]
    value=[i for i in range(97,100)]
    print(dict(zip(key,value)))
    答案:
    {'b': 98, 'a': 97, 'c': 99}
    
    通过‘’键值对‘’来创建字典
    dict(a=1,b=2,c=3) 
    答案:
    {'a': 1, 'b': 2, 'c': 3}
    
    a=dict(a=1,b=2,c=3)
    a.get('a')   #更加安全的字典元素访问方式
    答案:
    1
    a['a']
    答案: 
    1
    
    
    返回字典的键和值
    a.keys()
    答案:
    dict_keys(['b', 'c', 'a'])
    a.values()
    答案:
    dict_values([2, 3, 1])
    
    
    
    字典添加和修改
    a['age']=19 若该键不存在,则创建,否则修改
    a.update({'a':a,'b',b})对全部添加到a中,一样的键进行更新    
    
    
    Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
    str.join(sequence)
    
    a='asdfasd'
    '*.'.join(a)
    答案:
    'a*.s*.d*.f*.a*.s*.d'
    
    import random
    random.choice(list(range(5)))#随机选一个元素
    
    有序字典
    import collections
    x=collections.OrderedDict()
    x['a']=1
    x['b']=2
    x['c']=3
    print(x)
    答案:
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    
    集合运算
    a=set(range(5))
    b=set(range(3,8))
    print(a|b)  #
    print(a&b)  #
    print(a-b)  #
    print(a^b)  #对称差
    答案:
    {0, 1, 2, 3, 4, 5, 6, 7}
    {3, 4}
    {0, 1, 2}
    {0, 1, 2, 5, 6, 7}
    
    判断子集
    a={1,2,3}
    b={1,2,3,4}
    print(a.issubset(b))
    答案:
    True
    >>> 'a' in 'fdaaf'
    True
    
    #startswith  endswith  判断是否以指定字符串开始或结束
    s='中国人'
    print(s.startswith('中国'))
    print(s.startswith('中国',1))#从位置1开始查找
    答案:
    True
    False
    
    
    #它们还可以接受一个字符串元组作为参数来表示前缀或后缀
    import os
    name=[filename for filename in os.listdir(r'C:UsersAdministratorDesktop') if filename.endswith(('.png','.jpg'))]
    print(name)
    答案:
    ['0.jpg', '1484393555(1).png', '1484574032(1).png', '1484574235(1).png', '1484575013(1).png', '1484575722(1).png',
     '1487164690(1).png', '16110180021Qunxi Zhu.png', '532c0ed.png', '5807228.png', 'QQ图片20161212133524.jpg']
    
    isalnum,isalpha,isdigit,isspace,isupper,islower
    测试字符串是否数字或字母,是否为字母,是否为数字字符,是否为空白字符
    是否为答谢字母,是否为小写字母
    
    字符串居中,左对齐,右对齐centr,ljust,rjust
    s='Hello world!'
    print(s.center(20))
    print(s.center(20,'='))
    print(s.ljust(20,'='))
    print(s.rjust(20,'='))
    答案:
        Hello world!    
    ====Hello world!====
    Hello world!========
    ========Hello world!
    
    
    带有默认值参数的函数
    def f(a,b=100):
        return a+b
    print(f(1))
    print(f(1,2))
    答案:
    101
    3
    
    
    >>> ['asd ']*3
    ['asd ', 'asd ', 'asd ']
    >>> 'asd'*3
    'asdasdasd'
    >>> ('asd ')*3
    'asd asd asd '
    
    字典,列表作为默认参数值时,要特别小心
    def f(a,L=[]):
        L.append(a)
        return L
    print(f('5',[1,2,3,4]))
    print(f('aaa',['a','b']))
    print(f('a'))
    print(f('b'))
    答案:
    [1, 2, 3, 4, '5']
    ['a', 'b', 'aaa']
    ['a']
    ['a', 'b']  #在原来基础上加上了'b'
    
    def f(a,L=None):
        if L is None:
            L=[]
        L.append(a)
        return L
    print(f('5',[1,2,3,4]))
    print(f('aaa',['a','b']))
    print(f('a'))
    print(f('b'))  #变成'b'
    
    答案:
    [1, 2, 3, 4, '5']
    ['a', 'b', 'aaa']
    ['a']
    ['b']
    
    
    参数传递时,序列解包
    def f(a,b,c):
        print(a+b+c)
    f(*[1,2,3])
    dic={1:'a',2:'b',3:'c'}
    f(*dic)  #默认键
    f(*dic.values())
    
    hahaha并不一定要self
    class H:
        def __init__(hahaha,v):
            hahaha.value=v
        def show(hahaha):
            print(hahaha.value)
    a=H(3)
    a.show()
    答案:
    3
    import json
    str3 = '你好'
    print(str3)                # 你好,可以直接打印字符串
    print(type(str3))             # <class 'str'>,在内存中保存成Unicode数据
    print(json.dumps(str3))       # "u4f60u597d"
    
    c = str3.encode('utf8')       # 可以手动编码为bytes类型,二进制数据
    print(c)                      # b'xe4xbdxa0xe5xa5xbd',直接打印二进制数据,而不是字符内容
    print(type(c))                # <class 'bytes'>
    
    u = c.decode('utf8')          # 再次用utf-8解码为str字符串类型(Unicode数据)
    print(u)                      # 你好
    print(type(u))                # <class 'str'>,查看是Unicode数据
    print(json.dumps(u))          # "u4f60u597d"
    
    str4 = u'你好'
    print(str4)           # 你好,可以直接打印,没必要前面加u
    print(type(str4))             # <class 'str'>
    print(json.dumps(str4))       # "u4f60u597d"
    
    
    实例演示:字符串拼接,不同类型,肯定会报错
    
    print(b'hello'+'world')       # TypeError: can't concat str to bytes
    

      

  • 相关阅读:
    软件开发和机械制造的核心差别
    不做纯技术导向的程序员与中国特色的社会主义
    从代码里你可以看到什么?
    多少钱才可让人重拾理想
    项目经理一定比码农好么?
    技术还是管理?
    评李彦宏先生的内部邮件
    组织行为学对项目管理的意义(1)
    组织行为学对项目管理的意义:动机理论
    Silverlight与ashx通讯序列化DateTime时需注意的细节
  • 原文地址:https://www.cnblogs.com/skykill/p/7899921.html
Copyright © 2020-2023  润新知