Python基础

Python标准库 https://docs.python.org/zh-cn/3/library/index.html

Python知识点

1、用错命令:macOs 安装完 Python 后执行报错

应该使用 python3 而不是 python

Pip知识点

查看当前安装的包
pip3 list
查看当前pip的源
pip3 config list
永久修改pip源

pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip3 config set global.index-url https://pypi.doubanio.com/simple

更新pip至最新版本
python3 -m pip install --upgrade pip

Python基础

PyCharm注释模板

Editor -> File and Code Templates -> Python Script

"""
${NAME} - 

Author: ${USER}
Date: ${DATE}
"""
类型
# integer
a = 123
print(a, type(a))
print(type(a) == int)
# float
b = 1.23
print(b, type(b))
print(type(b) == float)
# string
c = 'hello'
print(c, type(c))
print(type(c) == str)
# boolean
d = True
print(d, type(d))
print(type(d) == bool)
# complex
e = 3 + 5j
print(e, type(e))
整数
# 十进制
a = 110
# 八进制
b = 0o110
# 十六进制
c = 0x110
# 二进制
d = 0b110
# 浮点数的科学计数法
e = 123e-5

# to binary
print(bin(47))
# to octal
print(oct(47))
# to hexadecimal
print(hex(47))
格式化输出
a1 = float(input('a1 = '))
b2 = float(input('b2 = '))

print(a1, '+', b2, '=', a1 + b2)
print('%.2f + %.2f = %.2f' % (a1, b2, a1 + b2))
print(f'{a1} + {b2} = {a1 + b2}:.2f')
运算符
# 赋值运算符 =
# 算术运算符 + - * / // % **
# 复合运算符 += -= *= /=
# 关系运算符 > < >= <= == != 
# 逻辑运算符 and or not
三元运算符

value_if_true if condition else value_if_false

如果condition为真,则整个表达式的值为value_if_true;如果condition的值为假,则整个表达式的值为value_if_false

range
  • range(101):可以用来产生0到100范围的整数,需要注意的是取不到101
  • range(1, 101):可以用来产生1到100范围的整数,相当于前闭后开
  • range(1, 101, 2):可以用来产生1到100的奇数,其中2是步长
  • range(100, 0, -1):可以用来产生100到1的偶数,其中-1是步长
容器
  • 列表(list)

    # 创建
    ## 字面量语法
    nums = [10, 100, 1000] 
    ## 构造器语法
    empty = list() 
    seq = list(range(1,100))
    ## 生成式(推导式)语法
    sqrt = [i ** 2 for i in range(1,10)] 
    
    # 操作
    nums.append(10000) 
    nums.insert(0, 1)
    nums.pop()
    nums.remove()
    del nums[0]
    nums.index(1000)
    nums.clear()
    ## 反转
    items = items[::-1]
    items.reverse()
    ## 排序(升序)
    items.sort()
    ## 排序(降序)
    items.sort(reverse=True)
    items.sort(key=int) # 将列表中数据按照整数的方式去排序
    
    # 元素个数
    len(nums)
    
    # 遍历
    for i in range(len(nums)):
      print(nums[i])
    
    for x in nums:
      print(x)
    
    for i, x in enumerate(nums):
      print(i, x)
    
    # 运算
    ## 重复运算
    repeat = [1, 10, 100] * 5
    ## 成员运算
    is_contains = 10 in repeat
    not_contains = 5 not in repeat
    ## 索引&切片:正向索引 0 ~ N-1 /  -N ~ -1
    ## 合并
    list1 = [1, 3, 5, 7]
    list2 = [4, 4, 8]
    print(list1 + list2)
    print(list1.extend(list2))
    ## 比较
    list1 = list(range(1, 8, 2))
    list2 = [1, 3, 5, 7, 9]
    ### 比较两个列表的元素是否一一对应相等
    print(list1 == list2)
    ### 比较两个列表对应元素的大小,从头开始比
    print(list1 > list2)
    
  • 元组(tuple)

    """不可变容器"""
    fruits1 = ('apple', 'banana', 'grape')
    # 重复运算
    print(fruits1 * 3)
    # 成员运算
    print('apple' in fruits1)
    print('grape' not in fruits1)
    # 合并运算
    fruits2 = ('pitaya', 'litchi')
    fruits3 = fruits1 + fruits2
    # 索引&切片
    print(fruits3[4], fruits3[-1])
    print(fruits3[1:4])
    print(fruits3[1:4:2])
    
    # pack / unpack
    a, b = 5, 10
    a, b, *c = 5, 10, 15, 20, 25 # a=5, b=10, c=[15, 20, 25]
    # ROT_TWO
    a, b = b, a
    # ROT_THREE
    a, b, c = b, c, a
    
  • 集合(set)

    """无序性&互异性的集合"""
    set1 = {1, 2, 3, 4, 5}
    set2 = {2, 4, 6, 8}
    empty = set() # 注意,set = {} 定义出来的不是集合,而是字典
    
    # 成员运算
    print(1 in set1)
    print(1 not in set2)
    
    # 交集
    print(set1 & set2)
    print(set1.intersection(set2))
    
    # 并集
    print(set1 | set2)
    print(set1.union(set2))
    
    # 差集
    print(set1 - set2)
    print(set1.difference(set2))
    
    # 对称差
    print(set1 ^ set2)
    print((set1 | set2) - (set1 & set2))
    print(set1.symmetric_difference(set2))
    
  • 字典(dict)
# 字面量语法
student1 = {"id": 1001, "name": "zhangsan", sex: 1, birthday: "1990-01-03"}
# 构造器语法
student2 = dict(id=1001, name="zhangsan", sex=1, birthday="1990-01-03")
# 生成式语法
dict1 = {i: i ** 2 for i in range(1, 10)}

# 遍历
for key in student1:
  print(key)

for value in student1.values():
  print(value)
  
for key, value in student1.items():
  print(key, value)

# 运算
print('name' in student1)

dict1 = {'A': 100, 'B': 200, 'C': 300}
dict2 = {'D': 400, 'E': 500, 'A': 600}

# 更新
dict1.update(dict2)
print(dict1)

# 删除
del dict1['A']
dict1.pop('B')
dict1.popitem()

# if key is in the dictionary, return its value. if not, insert key with a value of default and return default. default defaults to None.
dict1.setdefault('C')
dict1.setdefault('K', 1000)

# 清空
dict1.clear()
变量

全局变量 - 没有写在任何函数里面的变量

局部变量 - 定义在函数内部的变量

作用域

Python搜索一个变量是按照 LEGB 顺序进行搜索的

Local(局部作用域) --> Embeded(嵌套作用域,函数中可以嵌套函数) --> Global(全局作用域) --> Build-in(内置作用域,Python标准内置数据)

在函数中想使用全局变量,需要在变量中使用 global x = 200,想在嵌套函数中使用上一级的变量,需要在变量中使用 nonlocal x = 100

__name__

__name__是一个隐藏变量,它代表当前模块(文件)的名字

"""
example1.py
"""
if __name__ == '__main__':
  print("Hello world")

如果直接通过 Python 解释器运行 example.py 文件,__name__ 的值是 __main__

如果在其他的模块中导入 example.py,那么 example.py 中的 __name__ 的值就是 example

生成式语法

[expression for item in iterable if conditions]

expression:对应生成式列表的元素,是生成后需要保存的内容,expression通常利用for循环内的变量来计算表示,expression除了使用range循环外,不可忽略

for循环:语法对应基本的for循环,项item对应了可迭代对象iterable的每一个元素

if条件:用于判断循环的每个元素是否符合生成的要求标准,用于筛选循环的元素,因此不能再后面的if判断中使用else,否则失去嘞筛选的作用

# 生成一个n*n为元素的1-10的列表
list = [x*x for x in range(1,11)]

# 根据给定列表字符串集生成每个字符串的长度
list = ['ab', 'cde', 'fghj', 'jklmpb']
len_list = [len(x) for x in list]

# 生成30以内的偶数
list = [x for x in range(1, 31) if x%2==0]

# 多个整数的加法运算
def add(*args):
  total = 0
  for arg in args:
    if type(arg) in (int, float):
      total += arg
  return total

def add(*args):
  return sum([arg for arg in args if type(arg) in (int, float)])

print(add(1, 2, 'hello', 4))
参数
# 必备参数: 必须以正确的顺序传入函数,调用时的数量必须和声明时的一样
def multiprint(str, repeat):
  print(str*repeat)

multiprint('hello', 1)

# 关键字参数:和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值
# 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值
multiprint(repeat=3, str='my string')

# 默认参数:调用函数时,默认参数的值如果没有传入,则被认为是默认值
def multiprint(str, repeat=1)
    print(str*repeat)

multiprint('hello world')

# 不定长参数:一个函数能处理比当初声明时更多的参数,这些参数叫做不定长参数。不定长参数有两种
# *args:一个星号,将多个参数收集到一个“元组”对象中
# **kwargs: 两个星号,将多个参数收集到一个“字典”对象中
def test(*args, **kwargs):
  print(args, type(args))
  print(kwargs, type(kwargs))

test(1, 2, c=3, b=2, a=1, d='hello')
>>>(1, 2) <class 'tuple'>
>>>{'c': 3, 'b': 2, 'a': 1, 'd': 'hello'} <class 'dict'>

# 命名关键字参数:关键字参数对于传入的参数名无法限制。如果想对参数名有限制,就用到了命名关键字参数
# 命名关键字参数需要一个特殊分隔符 *,*后面的参数被视为命名关键字参数
def student(name, age, *, sports):
  print('name: ', name, 'age: ', age, 'sports: ', sports)

student('zhang', 23, sports='walking')
student('zhang', 23, eat='buff')
>>> Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
         student('wang', 23, eat='buff')
    TypeError: student() got an unexpected keyword argument 'eat'
函数

python中的函数是一等函数:

  • 函数可以作为函数的参数;

  • 函数可以作为函数的返回值;

  • 函数可以赋值给变量

如果把函数作为函数的参数或者返回值,这种通常称之为高阶函数。可以实现对原有函数的解耦合操作。

# fn 是一个实现二元运算的函数
def calc(init_val, fn, *args, **kwargs):
  total = init_val
  for arg in args:
    if type(arg) in (int, float):
      total = fn(total, arg)
  for value in kwargs.values():
    if type(value) in (int, float):
      total = fn(total, value)
  return total

def add(x, y):
  return x + y

def mul(x, y):
  return x * y

print(calc(0, add, 11, 22, 33, 44))
print(calc(1, mul, 11, 22, 33, 44))
lambda

匿名函数:指一类无需定义标识符(函数名)的函数或子程序

def add(x, y):
  return x + y
# 换成匿名函数
add = lambda x, y: x + y
print(add(2, 5))

def abs(x, y):
  if x > y:
    return x - y
  else
    return y - x
# 换成匿名函数
abs = lambda x, y: x - y if x > y else y - x
print(abs(4, 8))
map

map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterable返回

# 平方
def square(x):
  return x * x

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(map(square, numbers)))

# 结合lambda使用
print(list(map(lambda x: x*x, numbers)))
reduce

reduce函数接收两个参数,一个函数,一个Iterablereduce将函数结果继续和序列的下一个元素做累计计算,其效果就是:

reduce(func, [1,2,3]) -> func(func(1,2), 2)

# 加法
def add(x, y):
  return x + y

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(reduce(add, numbers))

# 结合lambda使用
print(reduce(lambda x: x + y, numbers))
filter

filter函数接收两个参数,一个函数,一个Iterablefilter把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

# 偶数
def even(i):
    return i%2==0
    
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(even, numbers)))

# 结合lambda使用
print(list(filter(lambda x: x%2==0, numbers)))

类的命名使用驼峰命名法

定义类:

  • 数据抽象 - 找到和对象相关的静态特征(属性)
  • 行为抽象 - 找到和对象相关的动态特征(方法)
# 学生对象
class Student:
  
  # 通过这个来限制外部动态增加属性
  __slots__ = ('name')
  
  def __init__(self, name):
    # 正常属性 public
    self.name = name
    # 私有属性 private 不允许外部直接修改应该加双_线
    self.__name = name  # private
  
stu = Student('lisi')
# python支持动态增加属性
stu.birthday = '1988-01'
继承
# 父类
class Person:
  
  def __init__(self, name):
    self.name = name
   
  def eat(self):
    print(f'{self.name}正在吃饭')
  
  def play(self, game_name):
    print(f'{self.name}正在玩{game_name}')
    
# 子类
class Student(Person):
  
  def __init__(self, name, grade):
    super().__init__(name)
    self.grade = grade
  
  def study(self, course_name):
    print(f'{self.name}正在学习{course_name}')
Union

Union是 typing 模块中定义的一个类,用于表示多个类型中的任意一种类型。Union类型可以用于表示参数或函数返回值等多种情况下可能的不同类型。
语法:typing.Union[type1, type2, ...]。使用Union类型注释能够有效地帮助代码维护者准确定义函数的输入和输出。需要注意的是,虽然 Union 类型可以用于灵活表示可选参数的类型,但是在实际使用时最好进行类型检查以确保参数类型正确。

from typing import Union

def get_int_or_str(value: Union[int, str, None]) -> Union[int, None]:
    if isinstance(value, (int, str)):
        return value
    else:
        return None
@Property

@Property 是 python 的一种装饰器,是用来修饰方法的
作用:@Property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。

class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 15
  def method_without_property(self): ##不含@property
      return 15

l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property())  #没有加@property , 必须使用正常的调用方法的形式,即在后面加()

与定义的属性配合,可以防止属性被修改

class DataSet(object):
    def __init__(self):
        self._images = 1
        self._labels = 2 #定义属性的名称
    @property
    def images(self): #方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
        return self._images 
    @property
    def labels(self):
        return self._labels
l = DataSet()
#用户进行属性调用的时候,直接调用images即可,而不用知道属性名_images,因此用户无法更改属性,从而保护了类的属性。
print(l.images) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,492评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,048评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,927评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,293评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,309评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,024评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,638评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,546评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,073评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,188评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,321评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,998评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,678评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,186评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,303评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,663评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,330评论 2 358

推荐阅读更多精彩内容

  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 5,826评论 2 16
  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 18,964评论 17 410
  • python优点: 简单易学 、免费开源、丰富的库、可扩展性、可移植性、面向对象、规范的代码。。。 缺点:...
    初学者菜鸟阅读 253评论 0 0
  • python基础一小时速成 python官网:python.org 解释器下载 官方文档 2.? 3.?版本 标准...
    空疏影阅读 582评论 0 0
  • 元组 1.什么时元组 容器型数据类型;不可变(不支持增删改)、有序(支持下标操作)将小括号作为容器的标志,多个元素...
    初学者009阅读 254评论 0 0