Python

作者: 阿V很简单 | 来源:发表于2018-02-08 13:37 被阅读0次

    Python笔记

    1. 文件类型

    .py

    • 最常见的类型

    .pyc

    • 该类型是.py文件编译后的二进制文件,运行效率当然比.py文件快啦

    • 编译的命令行如下:

        python -O-m py_compile hello.py
      

    .pyo

    • 经过优化编译的原文件,这个比.pyc效率更高

    2. 变量

    命名规则:

    • 变量可以是数字,字母,下划线组合,不能以数字开头

    简单理解:

    • Python中的变量类似是一个标签,贴向内存地址中的值,变量的重新赋值类似于标签移动

    3. 运算符和表达式

    赋值运算符

        = 等于,赋值
        += 加等
        -= 减等
        *= 乘等
        /= 除等
        % 求余等
    

    算术运算符

        + 加
        - 减
        * 乘
        / 除
        // 整除法
        % 求余数
        /** 幂  例如:  3**2 表示3的2平方为9
    

    关系运算符

        <
        >
        <=
        >=
        !=
        ==
    

    逻辑运算符

        and 逻辑与
        or 逻辑或
        not 逻辑非
    

    表达式概念

    • 将不同的数据(包括变量,函数)用运算符用一定的规则连接起来的一种式子

    4. 数据类型 (大部分计算机编程语言都有的定义,用一个盒子或者说空间把数据装起来)

    整型 int

        a = 123
        # type() 调用该函数可得到变量的数据类型
        print(type(a))
    
        输出:
        <type 'int'>
    

    长整型 long

        b = 999999999999999999999
        print(type(b))
        c = 99L
        print(type(c))
        输出:
        <type 'long'>
        <type 'long'>
    

    浮点型 float

        d = 13.0
        print(type(d))
        e = 5.0 / 2
        print(type(e))
    
        输出:
        <type 'float'>
        <type 'float'>
    

    复数类型 complex

        f = 3.14j
        print(type(f))
    
        输出
        <type 'complex'>
    

    字符串 str (序列类型数据)

        # ----单引号 ''
        str1 = 'hello world'
    
        # ----双引号 ""
        str2 = "hello world"
    
        # ----注意嵌套使用,转义字符
        str3 = "hello i'm hebw"
        str4 = "hello i'm \"hebw\""
    
        # ----三引号 """""" 可用于保存文字的格式,如下str5等同于str6
        str5 = """Tom:
        i'm hebw,nice to see you
        ok , see you again."""
        str6 = "Tom:\n\ti'm hebw,nice to see you\n\tok , see you again."
    
        # 占位符的使用
        def p(x, y):
            print("%s : %s" % (x, y))
        p(1, 2)
        p(*t)
    
        输出:
        1 : 2
    

    元组 tuple (序列类型数据)

    • 定义:
      通过圆括号,中间用逗号分隔元素定义,元组和字符串一样是不可变的

       # ----定义空元组
       t0 = ()
      
       # ----定义单元素元组
       t1 = (1,)
      
       # ----元组的值无法改变,以下代码将报错!!!
       t[1] = 31 报错!
      
    • 概念:
      发展出元组类型是有原因的,利用采用字符串储存userinfo = "milo 30 male",通过这个字符串可以存储一个人的信息,但是不太好操作,取出信息不能当做一个整体,而是通过索引来进行切片操作,因此诞生元组t = ('milo', 30, 'male')

    列表 list (序列类型数据)

    • 定义:通过中括号,中间用逗号分隔元素定义,列表中的值是可变的

        # ----定义一个空列表
        list2 = []
      
        # ----定义一个元素的列表
        list3 = [1]
      
    • 添加元素:

        list = [1, 2, 3]
        list.append(4)
        print(list) 
      
        输出:
        [1, 2, 3, 4]
      
    • 删除元素:

        # 按照元素删除,删除第一个出现的元素,其他元素不会删除
        list3 = [1, 2, 3, 4, 1]
        list3.remove(1)
        print(list3)    
      
        输出:
        [2, 3, 4, 1]
      
        # 按照索引删除
        list3 = [1, 2, 3, 4, 1]
        del (list3[0])
        print(list3)
        
        输出:
        [2, 3, 4, 1]
      
    • 修改元素:

        list3 = [1, 2, 3, 4, 1]
        list3[0] = 123456
        print(list3)
      
        输出:
        [123456, 2, 3, 4, 1]
      

    字典 dict

    • 定义:通过花括号,中间用逗号分隔元素定义.字典是Python中唯一的映射类型,无序性.

       # 通过{}创建
       dic = {0: 0, 1: 1, 2: 2}
      
       # 通过工厂方法dict()生成字典
       fdict = dict(['x', 1], ['y', 2])
      
       # fromkeys(),字典中的元素具有相同的值,默认为None,主要用于值一致的情况下
       ddict = {}.fromkeys(('x', 'y'), -1)
       ddict2 = {}.fromkeys(('x', 'y'))
       print(ddict)
       print(ddict2)
      
       输出:
       {'y': -1, 'x': -1}
       {'y': None, 'x': None}
      
    • 循环遍历字典 (注意无序性!)

       dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
      
       # 遍历key
       for key in dic5:
           print(key)
      
       # 遍历value
       for key in dic5:
           print(dic1[key])
      
       输出:
       gender
       age
       name
       male
       13
       hebw
       
       # 同时遍历key和value
       dict2 = {'a': 1, 'b': 2, 'c': 3}
       big = dict2.items()
       for k, v in big:
           print(k)
           print(v)
       
       输出:
       a
       1
       c
       3
       b
       2
      
    • 添加键值对

       dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
       dic5['tel'] = '13100000000'
       print(dic5)
      
       输出:
       {'gender': 'male', 'age': 13, 'tel': '13100000000', 'name': 'hebw'}
      
    • 删除键值对

        # del()删除key对应的键值对
        dic5 = {'gender': 'male', 'age': 13, 'tel': '13100000000', 'name': 'hebw'}
        del (dic5['tel'])
      
        # pop()删除key对应的键值对,并且返回该值
        dic5 = {'gender': 'male', 'age': 13, 'tel': '13100000000', 'name': 'hebw'}
        tel = dic5.pop("tel")
        print(dic5)
        print(tel)
      
    • 修改值

        dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
        dic5['name'] = 'HEBW'
        print(dic5)
        输出:
        dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
      
    • 清空字典

        dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
        dic5.clear()
      
    • 判空

        dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
        print("HEBW" in dic5)
        print("age" in dic5)
      
        输出:
        False
        True
      
    • 删除整个字典

        dic5 = {'name': 'hebw', 'age': 13, 'gender': 'male'}
        del (dic5)
        print(dic5)
      
        输出:
        会报错,提示dic5未定义
      
    • 根据key获取value

        # 如果存在则返回,不存在返回指定的值或none
        dic = {0: 0, 1: 1, 2: 2}    
        print(dic.get(13))
        print(dic.get(1, "error"))
        
        输出:
        None
        1
      
    • 获取字典中键(key)的列表

        dic = {0: 0, 1: 1, 2: 2}            
        print(dic.keys())
      
        输出:
        [0, 1, 2]
      
    • 获取字典中值(value)的列表

        dic = {0: 0, 1: 1, 2: 2}    
        print(dic.values())
      
        输出:
        [0, 1, 2]
      
    • 获取键值对元组的列表

        dic = {0: 0, 1: 1, 2: 2}
        print(dic.items())
      
        输出:
        [(0, 0), (1, 1), (2, 2)]
      

    序列类型基本操作

    索引:

    序列类型容器里的元素存在索引,第一个是从0开始往后递增,
    索引分正负,如下:
    s = abcde
     a b c d e
     0 1 2 3 4
    -5-4-3-2-1
    
    print(s[0] + s[1])
    print(s[-1] + s[-2])
    输出:
    ab
    ed
    

    切片:

    顾名思义,截取序列数据中的一部分内容
    
    
    # ----切片 [开始:结束:间隔默认为1,有调整切片方向的作用] 默认从左向右切片
    # ----切片 正索引
    print(s[0:1])
    print(s[:4])
    print(s[2:])
    print(s[2::2])
    
    输出:
    a
    abcd
    cde
    ce
    
    # ----切片 负索引
    print(s[-1])
    print(s[-1:])
    print(s[-1::-1])
    print(s[-4:-1])
    print(s[-1:-4:-1])
    print(s[-2:-5:-1])
    
    输出:
    e
    e
    edcba
    bcd
    edc
    dcb
    

    长度:

    str = 'abcde'
    print(len(str))
    
    输出:
    5
    

    连接:

    str = 'abcde'
    str2 = '12345'
    print(str + str2)
    
    输出:
    abcde12345
    

    重复:

    str2 = '12345'
    print(str2 * 5)
    
    输出:
    1234512345123451234512345
    

    存在判断:

    str2 = '12345'
    print('1' in str2)
    
    输出:
    True
    

    最大值:

    str = 'abcde'
    str2 = '12345'
    print(max(str))
    print(max(str2))
    
    输出:
    e
    5
    

    最小值:

    str = 'abcde'
    str2 = '12345'
    print(min(str))
    print(min(str2))
    
    输出:
    a
    1
    

    比较: 这个有点不懂?

    str = 'abcde'
    str2 = '12345'  
    print(cmp(str, str2))
    print(cmp(str, str))
    
    输出:
    1
    0
    

    遍历

    list = [1, 2, 3, 4, 5, 6, 7]
    str = 'hello'
    
    # 取出序列的值
    for x in list:
        print(x)
    for x in str:
        print(x)
    
    输出:
    1
    2
    3
    4
    5
    6
    7
    h
    e
    l
    l
    o
    
    # 取出序列的索引
    list = [1, 2, 3, 4, 5, 6, 7]
    for x in range(len(list)):
        print(x)
    
    输出:
    0
    1
    2
    3
    4
    5
    6
    

    流程控制语句

    基本使用

    # 两种结果
    a = 15
    if a > 124:
        print('a > 124')
        print('True')
    else:
        print('a < 124')
        print('False')
    
    输出:
    a < 124
    False
    
    # 三种结果
    a = 15
    if a > 124:
        print('a > 124')
        print('ok')
    elif a == 124:
        print("a == 124")
    else:
        print('a < 124')
        print('false')
    

    逻辑值

    True 表示非空的量
    False 表示0 NONE 空的量等
    

    循环控制语句

    else

    # 循环正常结束后调用 
    s = 'hello'
    for k in s:
        print(k)
    else:
        print("ending")
    
    输出:
    h
    e
    l
    l
    o
    ending
    

    break

    # 打断此层的循环
    for k in s:
        print(k)
        if k == 'l':
            break;
    else:
        print("ending")
    
    输出:
    h
    e
    l
    

    continue

    # 跳过循环的后续代码块
    for k in s:
        if k == 'l':
            continue;
        print(k)
    else:
        print("ending")
    
    输出:
    h
    e
    o
    ending
    

    return

    # 跳出循环结束函数返回数值
    def ret():
        for x in 'hello':
            print(x)
            if x == 'e':
                return 1
            print('666')
        else:
            print('-----ending')
    
    
    a = ret()
    print(a)
    
    输出:
    e
    1
    

    while循环

    # 基本使用
    x = ''
    while x != 'q':
        print(True)
        x = input('请输入q结束循环:')
        if not x:
            break;
        if x == 'c':
            print('one more time~~c')
    else:
        print('ending')
    

    函数

    设置默认参数

    def fa(name="hebw", age=0):
        print('name:%s' % name + '  age:%s' % age)
    fa()
    
    输出:
    name:hebw  age:0
    

    直接向函数传入元组

    # 类似这样的函数,形式参数类似一个元组
    def f(x, y):
        print x, y  
    # 这里有一个元组,如何把元组直接传入方法内.分别当做x,y
    t = (1, 2)
    # 这里使用这个方法来直接传入一个元组 利用一个*号
    f(*t)
    

    直接向函数传入字典

    def fa(name="hebw", age=0):
        print('name:%s' % name + '  age:%s' % age)
    fa(**{'age': 123, 'name': 'hbwwww'})
    
    输出:
    name:hbwwww  age:123
    

    冗余参数的接收

    # 使用元组接收冗余参数
    
    def f2(x, *args):
        print(x)
        print(args)
    f2(2, 1)
    
    输出:
    2
    (1,)
    
    # 使用字典接收冗余参数
    
    def f3(x, **args):
        print(x)
        print(args)
    f3(1)
    f3(1, y=1)
    
    输出:
    1
    {}
    1
    {'y': 1}
    

    lambda匿名函数

    # 普通函数
    def lam(x, y):
        return x + y
    a = lam(x=1, y=2)
    b = lam(*(3, 7))
    print(a)
    print(b)
    
    输出:
    3
    10
    
    # lambda函数
    def l(x, y):
        return x * y
    g = lambda x, y: x * y
    
    print(type(g))
    print(id(g))
    print(g)
    print(g(2, 2))
    
    输出:
    <type 'function'>
    39222184
    <function <lambda> at 0x0000000002567BA8>
    4
    
    # lambda用法举例
    l = range(1, 6)
    def fa(x, y):
        return x * y
    a = reduce(fa, l)
    c = reduce(lambda x, y: x * y, l)
    print(a)
    print(c)
    
    输出:
    120
    120
    

    switch场景,python不存在switch关键字,可以使用字典替代

    # 举例 设计一个计算器
    
    # 计算器
    def add(x, y):
        return x + y
    
    
    def jian(x, y):
        return x - y
    
    
    def cheng(x, y):
        return x * y
    
    
    def chu(x, y):
        return x / y
    
    # 用if 和 else 写的代码
    def operator(x, o, y):
        if o == "+":
            return add(x, y)
        elif o == '-':
            return jian(x, y)
        elif o == '*':
            return cheng(x, y)
        elif o == '/':
            return chu(x, y)
        else:
            pass
    
    
    print(operator(6, '+', 6))
    
    输出:
    12
    
    # 用字典的方法
    oper = {"+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y,
        '/': lambda x, y: x / y}
    
    def fc(x, o, y):
        print(oper.get(o)(x, y))
    
    fc(12, '/', 2)
    
    输出:
    6
    
    # 总结:
    # {}.get('o')('1', '2')
    # 前面的{}代表字典,利用get方法,获取字典对应的value,value可以是一个lambda方法,同时可以直接在后传入方法的参数
    

    内置函数

    abs() 返回数字的绝对值

    a = abs(-10111111)
    print(a)
    print(type(a))
    
    输出:
    10111111
    <type 'int'>
    

    max()最大 min()最小

    l = [1, 23, 4, 5, 6, 7, 8, 9, 0, 1, 3, 23, 2, 2, 31, 5, 7, 89, 34, 23, 'sd']
    print(max(l))
    print(min(l))
    
    输出:
    sd
    0
    

    divmod() 返回包含两个数字的商和余的元组

    print(divmod(2, 5))
    
    输出:
    (0,2)
    

    pow(x, y[, z]) 函数是计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z

    print(pow(2, 3, 4))
    
    输出:
    0
    

    round() 四舍五入

    print(round(12.4))
    
    输出:
    12.0
    

    callable() 检测函数是否可以被调用

    print(callable(round))
    
    输出:
    True
    

    isinstance() 判断对象是否属于某类型

    l2 = {1: 1, 2: 2}
    print(isinstance(l2, tuple))
    
    输出:
    False
    

    cmp() 判断两个字符串是否一样

    print(cmp('1', '1'))
    print(cmp('1', '2'))
    print(cmp('2', '1'))
    
    输出:
    0
    -1
    1
    

    xrange()相比range(),就说是效率高一点,具体用处不明啊

    类型转换

    print(type(int(123)))
    print(type(long(123)))
    print(type(float(123)))
    print(type(tuple([1, 2])))
    print(type(list((1,))))
    print(type(str(1)))
    
    输出:
    <type 'int'>
    <type 'long'>
    <type 'float'>
    <type 'tuple'>
    <type 'list'>
    <type 'str'>

    相关文章

      网友评论

          本文标题:Python

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