美文网首页
python - 学习笔记

python - 学习笔记

作者: 自走炮 | 来源:发表于2020-10-07 18:10 被阅读0次
    • 其他
      • 变量值交换
      • 展开变量
      • 条件判断
      • 字符串嵌变量
      • 数组循环
      • 数组查重
      • 数组排序
      • 数组内包
      • 错误处理 和 with

    其他

    变量值交换

    x, y = 100, 200
    x, y = y, x
    

    展开变量

    mylist = [100, 200]
    newlist = [*mylist, 300, 400]
    mydic = { "name": "test", "time": 2016 }
    newdic = { **mydic, "price": 1000 }
    

    条件判断

    myprofile = { "name": "koma", "age": 25 }
    if "age" in myprofile and myprofile["age"] <= 30:
        print("年轻有为")
    # 变量 = 真值 if 条件 else 假值
    score = 15
    result = "超级" if score >= 20 else "普通"
    print(result)
    

    字符串嵌变量

    dbname = "PostgreSql"
    print("学习" + dbname) # 字符串连接
    print(f"学习{dbname}") # f文字串
    print("学习{0}".format(dbname)) # format函数
    print("学习%s" % dbname) # %
    

    数组循环

    mylist = [1, 2, 3, 5, 8, 13]
    for index in range(len(mylist)):
        print(mylist[index], end=' ')
    for val in mylist:
        print(val, end=' ')
    for index, val in enumerate(mylist):
        print(index, val)
    # 倒序
    for val in reversed(mylist):
        print(val, end=' ')
    for index, val in enumerate(reversed(mylist)):
        print(index, val)
    # 字典
    mydic = { "name": "test", "time": 2016, "price": 1000 }
    for key in mydic:
        print('key:', key, 'value:', mydic[key], end=', ')
    for key, val in mydic.items():
        print('key:', key, 'value:', val, end=', ')
    

    数组查重

    mytest1 = [1, 2, 3, 3, 5]
    mytest2 = ['a', 'b', 'c', 'c', 'd']
    print(list(set(mytest1)))
    print(list(set(mytest2)))
    

    数组排序

    mylist = [21, 1, 2, 3, 5, 8, 13]
    print(sorted(mylist, reverse=True)) # 降序排列
    mylist = [[2, 20], [1, 10], [3, 30]]
    print(sorted(mylist, key=lambda item: item[1])) # 指定排序 key
    mylist = [
        { "name": "curry", "age": 32 },
        { "name": "lebron", "age": 36 },
        { "name": "harden", "age": 31 },
    ]
    print(sorted(mylist, key=lambda item: item["age"])) # 字典排序
    

    数组内包

    mytest = []
    for i in range(5):
        mytest.append(i*i)
    mytest = [i*i for i in range(10)] # 内包
    

    错误处理 和 with

    myfile = open("sample/test.json", "r")
    try:
        content = myfile.read()
        raise Exception('test')
    except:
        pass
    finally:
        myfile.close()
    # with 句柄自动关闭
    with open("sample/test.json", "r") as myfile:
        content = myfile.read()
    

    相关文章

      网友评论

          本文标题:python - 学习笔记

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