前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 基础语法笔记

python 基础语法笔记

作者头像
LinkinStar
发布2022-09-01 13:58:59
2560
发布2022-09-01 13:58:59
举报
文章被收录于专栏:LinkinStar's BlogLinkinStar's Blog

记录python的一些基础语法,用于查阅

列表和元组

  • 列表和元组都是有序的,可以存储任意数据类型的集合
  • 列表是动态的,长度可变,存储空间和性能略逊与元组
  • 元组是静态的,长度大小固定,不能增加修改
  • 创建一个列表使用 empty_list = [] 相比于 list() 更好,因为 [] 底层走的c,而 list() 是函数,更加贵
代码语言:javascript
复制
l = [1, 2, 3, 4]

tup = (1, 2, 3, 4)

list((1, 2, 3))
[1, 2, 3]
l.count(3)
l.index(7)
l.reverse()
l.sort()
l.append(4)
# extend会将里面的元素添加进去,而append会直接将[1,2]作为一个元素加入
l.extend([1,2])

tuple([1, 2, 3])
(1, 2, 3)
tup.count(3)
tup.index(7)
list(reversed(tup))
sorted(tup)

字典和集合

本质就是hash表

  • 删除会赋值为特殊值并在rehash调整大小的时候进行处理
  • 会保留1/3的大小,小于时扩容并rehash
  • 可变元素不能作为key
代码语言:javascript
复制
# 初始化
d1 = {'name': 'jason', 'age': 20, 'gender': 'male'}
d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
d4 = dict(name='jason', age=20, gender='male') 
d1 == d2 == d3 == d4
True

# 赋值
d['name']= 'xiaoming'

# 获取值
d['name']
d.get('name')
d.get('name', 'null')

# 删除
d.pop('name')

# 是否存在
'name' in d
True

# 排序
d = {'b': 1, 'a': 2, 'c': 10}
d_sorted_by_key = sorted(d.items(), key=lambda x: x[0]) # 根据字典键的升序排序
d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 根据字典值的升序排序d_sorted_by_key

# 初始化
s1 = {1, 2, 3}
s2 = set([1, 2, 3])
s1 == s2
True

# 基操
s.add(4)
s.remove(1)
sorted(s)

字符串

  • 三个引号用于多行
  • 字符串为不可变的
代码语言:javascript
复制
# 一样的
'123'
"123"
"""123"""

name = 'jack'
name[0]
name[1:3]

# 遍历
for char in name
	print(char)

# 替换
s.replace('h', 'n')

# 连接
s += 'a'
'-'.join(['aaa','bbb'])

# 分离
'1-1-1-1-2'.split('-')

# 去掉开头结尾
string.strip(str)
string.ltrip(str)
string.rtrip(str)

# 从开始到结尾进行查找
string.find(sub, start, end)

# 数字到字符串,字符串到数字
str(1)
int('1')

# 格式化
>>> print('id: {}, name: {}'.format("1", "xiaowang"))
id: 1, name: xiaowang

输入输出

  • 使用with会自动关闭打开的文件
代码语言:javascript
复制
name = input('your name:')

with open('in.txt', 'r') as fin:
    text = fin.read()

with open('out.txt', 'w') as fout:
    fout.write('123')

json操作

代码语言:javascript
复制
# 序列化对象为json字符串
json.dumps(params)

# 反序列化json字符串
json.loads(params_str)

条件

  • 使用elif
  • 后面要有冒号
  • 条件内为空的均为false
代码语言:javascript
复制
if id == 0:
    print('red')
elif id == 1:
    print('yellow')
else:
    print('green')

循环

代码语言:javascript
复制
l = [1, 2, 3, 4]

# 遍历元素
for item in l:
    print(item)

# 遍历下标
for index in range(0, len(l)):
    if index < 5:
        print(l[index])

# 下标和元素同时需要,使用enumerate
for index, item in enumerate(l):
    if index < 5:
        print(item)

# while当然也可以
while index < len(l):
    print(l[index])
    index += 1

# 单行操作,很简洁
expression1 if condition else expression2 for item in iterable

for item in iterable:
    if condition:
        expression1
    else:
        expression2

expression1 for item in iterable if condition

for item in iterable:
    if condition:
        expression1

异常处理

  • json反序列化的时候需要异常处理
  • 文件需要异常处理
  • 必要的时候才进行异常处理
代码语言:javascript
复制
try:
    s = input('please enter two numbers separated by comma: ')
    num1 = int(s.split(',')[0].strip())
    num2 = int(s.split(',')[1].strip())
    ... 
except ValueError as err:
    print('Value Error: {}'.format(err))
finally:
    print('finally')

print('continue')
...

except (ValueError, IndexError) as err:

# OR
except ValueError as err:
    print('Value Error: {}'.format(err))
except IndexError as err:
    print('Index Error: {}'.format(err))
except:
    print('Other error')

# 自定义异常
class MyInputError(Exception):
    """Exception raised when there're errors in input"""
    def __init__(self, value): # 自定义异常类型的初始化
        self.value = value
    def __str__(self): # 自定义异常类型的 string 表达形式
        return ("{} is invalid input".format(repr(self.value)))
    
try:
    raise MyInputError(1) # 抛出 MyInputError 这个异常
except MyInputError as err:
    print('error: {}'.format(err))

函数

  • 要先定义在上面
  • 使用的时候才会创建
  • 内部变量作用域只在函数内部
  • 不能在函数内部随意改变全局变量的值
  • 对于嵌套函数来说,内部函数可以访问外部函数定义的变量,但是无法修改,若要修改,必须加上 nonlocal 这个关键字
代码语言:javascript
复制
# 不需要申明类型
def my_sum(a, b):
    return a + b

# 设置默认值
def func(param = 0):

# 函数定义嵌套,内部函数无法被外部直接调用
def f1():
    print('hello')
    def f2():
        print('world')
    f2()
f1()

def outer():
    x = "local"
    def inner():
        nonlocal x # nonlocal 关键字表示这里的 x 就是外部函数 outer 定义的变量 x
        x = 'nonlocal'
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# 输出
inner: nonlocal
outer: nonlocal

# 闭包,就是返回一个函数而已
def nth_power(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of # 返回值是 exponent_of 函数
 
square = nth_power(2) # 计算一个数的平方
cube = nth_power(3) # 计算一个数的立方

匿名函数

  • lambda 是一个表达式(expression),并不是一个语句(statement)
  • lambda 的主体是只有一行的简单表达式,并不能扩展成一个多行的代码块
代码语言:javascript
复制
lambda argument1, argument2,... argumentN : expression

square = lambda x: x**2
square(3)

常用函数

代码语言:javascript
复制
# map函数,对于集合内每个元素都做一次func
l = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, l) # [2, 4, 6, 8, 10]

# filter函数,对于集合内每个元素都做一次func,并返回true或者false,结果返回为true的集合
l = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, l) # [2, 4]

# reduce函数,集合内每个元素都做一次func,最后将结果组合
l = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, l) # 1*2*3*4*5 = 120

代码语言:javascript
复制
class Document():
    
    WELCOME_STR = 'Welcome! The context for this book is {}.'
    
    def __init__(self, title, author, context):
        print('init function called')
        self.title = title
        self.author = author
        self.__context = context
    
    # 类函数
    @classmethod
    def create_empty_book(cls, title, author):
        return cls(title=title, author=author, context='nothing')
    
    # 成员函数
    def get_context_length(self):
        return len(self.__context)
    
    # 静态函数
    @staticmethod
    def get_welcome(context):
        return Document.WELCOME_STR.format(context)
 
 
empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove')
 
 
print(empty_book.get_context_length())
print(empty_book.get_welcome('indeed nothing'))
 
########## 输出 ##########
 
init function called
7
Welcome! The context for this book is indeed nothing.

模块化

  • 巧用if name == ‘main‘来避开 import 时执行
代码语言:javascript
复制
# 引入utils包下的util文件的get_sum方法
from utils.utils import get_sum

# 直接从项目根目录中导入,并依次向下导入模块 mat.py 中的 Matrix
from proto.mat import Matrix

import module_name
from module_name import * 
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 列表和元组
  • 字典和集合
  • 字符串
  • 输入输出
  • json操作
  • 条件
  • 循环
  • 异常处理
  • 函数
  • 匿名函数
  • 常用函数
  • 模块化
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档